Node.js 笔记 4

Promise A+

 

有三种状态,pending(进行中)、fulfilled(已成功)、rejected(已失败)

  • 复习Promise的使用
    • 非管控异步操作
    • 管控异步操作
    • then中两个参数
    • then和catch
    • then链
    • then中返回新的Promise
    • Promise.all
    • new Promise((resolve, reject) => {
          //=>RESOLVE & REJECT:是自己任意执行的,但是大家都约定成功执行RESOLVE,失败执行REJECT
          //=>EXCUTOR函数(执行函数)中可以不管控异步操作(但是不管控异步没啥意义)
          resolve(100);
      }).then(result => {
          //=>RESOLVE执行的时候会触发第一个回调函数执行
          console.log(1);
          return 1000;//=>会把这个值传递给下一个THEN中的方法,如果返回的是一个新的Promise实例,则等到Promise处理完成,把处理完成的结果传递给下一个THEN
      }, reason => {
          //=>REJECT执行的时候会触发第二个回调函数执行
          console.log(2);
      }).then(result => {//=>需要保证执行THEN方法返回的依然是PROMISE实例,这样才可以实现链式调用
          //=>上一个THEN中管控的两个方法只要任何一个执行不报错,们都会执行这个THEN中的第一个方法,如果执行报错,会执行此THEN中的第二个回调函数
      }).catch(reason => {
          //=>CATCH就相当于THEN(null,reason=>{})
      });
      console.log(3);
      
      //=>等待所有的PROMISE都成功执行THEN,反之只要有一个失败就会执行CATCH
      Promise.all([promise1, ...]).then();
  • 基于Promise A+规范,自己创造一个原生的Promise库
class Promise {
    constructor(excutorCallBack) {
        this.status = 'pending';
        this.value = undefined;
        this.fulfilledAry = [];
        this.rejectedAry = [];

        //=>执行EXCUTOR(异常捕获)
        let resolveFn = result => {
            let timer = setTimeout(() => {
                clearTimeout(timer);
                if (this.status !== 'pending') return;
                this.status = 'fulfilled';
                this.value = result;
                this.fulfilledAry.forEach(item => item(this.value));
            }, 0);
        };
        let rejectFn = reason => {
            let timer = setTimeout(() => {
                clearTimeout(timer);
                if (this.status !== 'pending') return;
                this.status = 'rejected';
                this.value = reason;
                this.rejectedAry.forEach(item => item(this.value));
            }, 0);
        };
        try {
            excutorCallBack(resolveFn, rejectFn);
        } catch (err) {
            //=>有异常信息按照REJECTED状态处理
            rejectFn(err);
        }
    }

    then(fulfilledCallBack, rejectedCallBack) {
        //=>处理不传递的状况
        typeof fulfilledCallBack !== 'function' ? fulfilledCallBack = result => result : null;
        typeof rejectedCallBack !== 'function' ? rejectedCallBack = reason => {
            throw new Error(reason instanceof Error ? reason.message : reason);
        } : null;

        //=>返回一个新的PROMISE实例
        return new Promise((resolve, reject) => {
            this.fulfilledAry.push(() => {
                try {
                    let x = fulfilledCallBack(this.value);
                    x instanceof Promise ? x.then(resolve, reject) : resolve(x);
                } catch (err) {
                    reject(err);
                }
            });
            this.rejectedAry.push(() => {
                try {
                    let x = rejectedCallBack(this.value);
                    x instanceof Promise ? x.then(resolve, reject) : resolve(x);
                } catch (err) {
                    reject(err);
                }
            });
        });
    }

    catch(rejectedCallBack) {
        return this.then(null, rejectedCallBack);
    }

    static all(promiseAry = []) {//=>Promise.all()
        return new Promise((resolve, reject) => {
            //=>INDEX:记录成功的数量 RESULT:记录成功的结果
            let index = 0,
                result = [];
            for (let i = 0; i < promiseAry.length; i++) {
                //=>promiseAry[i]:
                //每一个需要处理的PROMISE实例
                promiseAry[i].then(val => {
                    index++;
                    result[i] = val;//=>索引需要和promiseAry对应上,保证结果的顺序和数组顺序一致
                    if (index === promiseAry.length) {
                        resolve(result);
                    }
                }, reject);
            }
        });
    }
}

module.exports = Promise;

使用

let Promise = require('./6-promise');

/*let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        // Math.random() < 0.5 ? resolve(100) : reject(-100);
        resolve(100);
    }, 1000);
});

let p2 = p1.then(result => {
    throw new Error('ERROR');
    return result + 100;
});

let p3 = p2.then(null);

p3.then(result => {
    console.log(result);
}, reason => {
    console.log(1, reason);
}).catch(reason => {
    console.log(2, reason);
});

console.log(3);*/

let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject(100);
    }, 50);
});

let p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject(200);
    }, 10);
});

let p3 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(300);
    }, 80);
});

Promise.all([p1, p2, p3]).then(result => {
    //=>所有的PROMISE都成功执行,RESULT中分别存储每一个实例返回的结果,而且和数组中的顺序是一样的
    console.log(result);
}).catch(reason => {
    //=>只要有有一个失败,就执行这个方法,失败后不再执行后面的操作
    console.log(reason);
});

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值