在浏览器控制台输入如下代码,可以看到Promise原型对象信息。
var p = new Promise(()=>{});console.log(p)
Promise原型上有catch、finally、then等方法。同时Promise内部维护了两个属性值status和value
再看Promise的构造方法,如下图
构造函数有all、allSettled、finally、race、reject、resolve等方法。
构造函数实现总结:
构造函数接受一个函数executor,并立即执行;executor函数接受两个参数,一个是resolve函数,一个是rejected函数,用于后续回调执行;promise对象的then方法中的第一个参数(函数)是状态变为fulfilled时的回调。resolve函数被调用时,会触发then方法中的回调函数的指定。 const PENDING = 'pending';const FULFILLED = 'fullfilled';const REJECTED = 'rejected';function Promise(executor) { this.status = PENDING; this.value = undefined; this.onResolvedCallback = []; //成功状态下的回调函数集合 this.onRejectedCallback = []; function resolve(value) { }; function reject() { }; executor(resolve, reject);} const PENDING = 'pending';const FULFILLED = 'fullfilled';const REJECTED = 'rejected';function Promise(executor) { this.status = PENDING; this.value = undefined; this.onResolvedCallback = []; //成功状态下的回调函数集合 this.onRejectedCallback = []; function resolve(value) { if(this.status === PENDING) { this.status = FULFILLED; this.value = value; // 触发后续then方法中的回调方法执行 onRejectedCallback.forEach(onResolved => { onResolved(value) }); } }; function reject() { }; try { // 考虑到执行executor的过程中有可能出错,所以我们用try/catch块给包起来,并且在出错后以catch到的值reject掉这个Promise executor(resolve, reject) // 执行executor } catch(e) { reject(e) }}`` 参考https://www.jianshu.com/p/b4f0425b22a1
https://github.com/xieranmaya/blog/issues/3