第一步:Promise构造函数接受一个函数作为参数,该函数的两个参数分别是:resolve和reject;
function Promise(task) { // 缓存this let that = this // 进行中的状态 this.status = 'pending' //初始值 this.value = undefined // 存放成功后要执行的回调函数的序列 that.onResolvedCallbacks = [] // 存放失败后要执行的回调函数的序列 that.onRejectCallbacks = [] // 该方法将Promise由pending变为fulfiled function resolve(value) { if(that.status == 'pending') { that.status = 'fulfiled' that.value = value that.onResolvedCallbacks.forEach(cb => cb(that.value)) } } // 该方法是将Promise由pending变成rejected function reject(reason) { if(that.status == 'pending') { that.status = 'rejected' that.value = reason that.onRejectCallbacks.forEach(cb => cb(that.value)) } } try { // 每一个Promise在new一个实例的时候 接受的函数都是立即执行的 task(resolve, reject) } catch(e) { reject(e) } }
第二部 写then方法,接收两个函数onFulfilled onRejected,状态是成功态的时候调用onFulfilled 传入成功后的值,失败态的时候执行onRejected,传入失败的原因,pending 状态时将成功和失败后的这两个方法缓存到对应的数组中,当成功或失败后 依次再执行调用
Promise.prototype.then = function(onFulfilled, onRejected) { if(this.status == 'fulfiled') { onFulfilled(this.value) } if(this.status == 'rejected') { onRejected(this.value) } if (this.status == 'pending') { this.onResolvedCallbacks.push(onFulfilled(this.value)); this.onRejectCallbacks.push(onRejected(this.value)); } } new Promise(function (resolve, reject) { resolve(100);// reject(100) }).then(function (data) { console.log('666', data) })