核心思想即把then后的函数提取出来等待resolve后执行callbacks
function _Promise(fn, callbacks) {
var value = null;
var callbacks = callbacks || [];
var state = 'pending';
var _this = this;
this.then = function (fulfilled, rejected) {
return new _Promise(function (resolv, rejec) {
try {
if (state == 'pending') {
callbacks.push(fulfilled);
return;
}
if (state == 'fulfilled') {
var data = fulfilled(value) || value;
resolv(data);
return;
}
if (state == 'rejected') {
var data = rejected(value);
resolv(data);
return;
}
} catch (e) {
_this.catch(e);
}
}, callbacks);
}
function resolve(valueNew) {
value = valueNew;
state = 'fulfilled';
execute();
}
function reject(valueNew) {
value = valueNew;
state = 'rejected';
execute();
}
function execute() {
setTimeout(function () {
callbacks.forEach(function (cb) {
value = cb(value);
});
}, 0);
}
this.catch = function (e) {
console.error(JSON.stringify(e));
}
fn(resolve, reject);
}
复制代码
转载于:https://juejin.im/post/5d47b6ee518825052a032173