function Promise(fn) {
var state = 'pending',
value = '',
callbacks = [];
this.then = function(onfulfilled) {
if(state === 'pending') { // 判断状态,当执行过resolve,之后链式的then直接执行
callbacks.push(onfulfilled);
return this;
}
onfulfilled(value);
return this;
}
function resolve(newValue) {
value = newValue;
state = 'fulfilled';
callbacks.forEach(function(callback) {
callback(value)
})
}
fn(resolve)
}
上面代码存在一个问题,在then方法注册回调之前,resolve就已经执行了,为了保证注册回调在resolve之前执行,可以通过延时将resolve执行回调的方法放到执行队列队尾。
function resolve(newValue) {
value = newValue;
state = 'fulfilled';
setTimeout(function() {
callbacks.forEach(function(callback) {
callback(value)
})
})
}
var hcx = new Promise(function(resolve) {
resolve(‘my name is hcx!’)
}).then(function(result) {
// do something
})
加入失败处理:
function Promised(fn) {
var callbacks = [],
value = '',
state = 'pending';
this.then = function(onFulfilled, onReject) {
return new Promised(function(resolve, reject) {
handle({
onFulfilled: onFulfilled,
onReject: onReject,
resolve: resolve,
reject: reject
})
})
}
function handle(callback) {
if(state === 'pending') {
callbacks.push(callback);
return;
}
var cb = state === 'fulfilled'? callback.onFulfilled: callback.onRejected;
if(!cb) {
cb = state === 'fulfilled'? callback.resolve: callback.reject;
cb(value);
return;
}
try {
callback.resolve(cb(value));
} catch(err) {
callback.reject(err);
}
}
function resolve(data) {
value = data;
state = 'fulfilled';
execute();
}
function reject(data) {
value = data;
state = 'rejected';
execute();
}
function execute() {
setTimeout(function() {
for(var i = 0; i < callbacks.length; i++) {
handle(callbacks[i]);
}
});
}
fn(resolve, reject);
}