1、简单的promise:
//极简promise雏形 function Promise(fn){ var value = null; callbacks = [];//callback为数组,因为可以同时有很多个回调 this.then = function(onFulfilled){ callbacks.push(onFulfilled); } function resolve(value){ callbacks.forEach(function(callback){ callback(value); }); } fn(resolve); }
上面:
1、调用then方法,将想要在Promise异步操作成功时执行的回调放入callbacks队列,其实也就是注册回调函数。
2、创建Promise实例时传入的函数会被赋予一个函数类型的参数,即resolve,它接收一个参数value,代表异步操作返回的结果,当异步操作执行成功后,用户会调用resolve方法,这时候其实真正执行的操作是将callbacks队列的回调一一执行。
//链式 this.then=function(onFulfilled){ callbacks.push(onFulfilled); return this; }
//改造resolve函数保证异步执行 function resolve(value){ setTimeout(function(){ callbacks.forEach(function (callback){ callback(value); },0); }) }
//状态 pending fulfilled function Promise(fn){ var state ="pending"; value = null; callbacks=[]; this.then = function(onFulfilled){ if(state === 'pending'){ callbacks.push(onFulfilled); return this; } }; function resolve(newValue){ value = newValue; state = 'fulfilled'; setTimeout(function(){ callbacks.forEach(function(callback){ callback(value); }); },0); } fn(resolve); }