function Promise(fn) { var value = null, callbacks = []; //callbacks为数组,因为可能同时有很多个回调 this.then = function (onFulfilled) { callbacks.push(onFulfilled); }; function resolve(value) { callbacks.forEach(function (callback) { callback(value); }); } fn(resolve); }
1、定义回调函数队列callbacks数组
2、定义this.then方法,给队列添加方法 callback
3、定义resolve方法,执行回调函数callback
4、在fn里传入resolve,作为参数