「日更_ES6」3. Promise

46 阅读2分钟

前言:积跬步第三天 Promise

Promise 是 ES6 引入的异步编程的新解决方案。语法上 Promise 是一个构造函数, 用来封装异步操作并可以获取其成功或失败的结果。

Promise基本语法

//实例化 Promise 对象 
//形参 resolve 成功/ reject 失败
const p = new Promise(function(resolve, reject){
    setTimeout(function(){
    
        // let data = '数据库中的用户数据';
        // resolve
        // resolve(data); //对象(p)的状态变为成功

        let err = '数据读取失败'; 
        reject(err); // 对象(p)的状态变为失败
        
        // 既不调用 resolve 也不调用 reject 状态为初始态 pendding
    }, 1000);
});

//调用 promise 对象的 then 方法
p.then(function(value){
    console.log(value); // 成功
}, function(reason){
    console.error(reason); // 失败
})

Promise封装AJAX请求

// 接口地址: https://api.apiopen.top/getJoke
const p = new Promise((resolve, reject) => {
    //1. 创建对象
    const xhr = new XMLHttpRequest();

    //2. 初始化
    xhr.open("GET", "https://api.apiopen.top/getJ");

    //3. 发送
    xhr.send();

    //4. 绑定事件, 处理响应结果
    xhr.onreadystatechange = function () {
        //判断
        if (xhr.readyState === 4) {
            //判断响应状态码 200-299
            if (xhr.status >= 200 && xhr.status < 300) {
                //表示成功
                resolve(xhr.response);
            } else {
                //如果失败
                reject(xhr.status);
            }
        }
    }
})

//指定回调
p.then(function(value){
    console.log(value);
}, function(reason){
    console.error(reason);
});

Promsie封装读取文件

//1. 引入 fs 模块
const fs = require('fs');

//2. 调用方法读取文件
// fs.readFile('./resources/为学.md', (err, data)=>{
//     //如果失败, 则抛出错误
//     if(err) throw err;
//     //如果没有出错, 则输出内容
//     console.log(data.toString());
// });

//3. 使用 Promise 封装
const p = new Promise(function(resolve, reject){
    fs.readFile("./resources/为学.mda", (err, data)=>{
        //判断如果失败
        if(err) reject(err);
        //如果成功
        resolve(data);
    });
});

p.then(function(value){
    console.log(value.toString());
}, function(reason){
    console.log("读取失败!!");
});

Promise then方法

//创建 promise 对象
const p = new Promise((resolve, reject)=>{
    setTimeout(()=>{
        resolve('用户数据');
        // reject('出错啦');
    }, 1000)
});

// 调用 then 方法  then方法的返回结果是 Promise 对象, 对象状态由回调函数的执行结果决定

// 1. 如果回调函数中返回的结果是 非 promise 类型的属性, 状态为成功, 返回值为对象的成功的值
// 2. 如果回调函数中返回的结果是 promise ,则返回的promise状态决定了then方法返回promise的对象状态,返回值为promise返回的值
// 3. 如果回调函数抛出错误,then方法返回失败状态,抛出的错误值为失败值
const result = p.then(value => {
    console.log(value);
    //1. 非 promise 类型的属性
    // return 'iloveyou';
    //2. 是 promise 对象
    // return new Promise((resolve, reject)=>{
    //     // resolve('ok');
    //     reject('error');
    // });
    //3. 抛出错误
    // throw new Error('出错啦!');
    throw '出错啦!';
}, reason=>{
    console.warn(reason);
});

//链式调用 解决回调地狱
p.then(value=>{

}).then(value=>{

});

Promise catch方法

const p = new Promise((resolve, reject)=>{
    setTimeout(()=>{
        //设置 p 对象的状态为失败, 并设置失败的值
        reject("出错啦!");
    }, 1000)
});

// p.then(function(value){}, function(reason){
//     console.error(reason);
// });

p.catch(function(reason){
    console.warn(reason);
});