雏形
function Promise(fn) {
var value = null,
callbacks = []; //callbacks为数组,因为可能同时有很多个回调
this.then = function (onFulfilled) {
callbacks.push(onFulfilled);
};
function resolve(value) {
setTimeout(function() {
callbacks.forEach(function (callback) {
callback(value);
});
}, 0)
}
fn(resolve);
}
剩下的就是加入状态啦,回调支持reject啦
注意resolve
中的setTimeout
,是为了解决resolve()
发生在then
注册回调之前,如:
const p = new Promise(resolve => {
resolve("finished");
});
p.then(result => console.log(`result is ${result}`))