参考 http://www.tuicool.com/articles/RzQRV3
var PENDING = undefined,
FULLFILLED = 1,
REJECTED = 2;
var Promise = function(resolver) {
var promise = this;
this.value;
this.reason;
this.status = PENDING;
this.resolver;
this.rejecter;
var resolve = function(value) {
promise.value = value;
promise.status = FULLFILLED;
if (promise.resolver || promise.rejecter) {
var ret = promise.resolver.call(null, promise.value);
if(ret instanceof Promise) {
ret.then(promise.resolver_relsolve);
} else {
promise.resolver_relsolve(promise.value);
}
}
}
var reject = function(err) {
promise.value = err;
promise.status = REJECTED;
if (promise.resolver || promise.rejecter) {
var ret = promise.rejecter.call(null, promise.value);
if(ret instanceof Promise) {
ret.then(function(){}, promise.rejecter_reject);
} else {
promise.rejecter_reject(promise.value);
}
}
}
resolver(resolve, reject);
}
// Promise then 方法
Promise.prototype.then = function(onFulfilled, onRejected) {
var promise = this;
if (promise.status == FULLFILLED) {
var ret = onFulfilled(promise.value);
if(ret instanceof Promise) {
return ret;
} else {
return new Promise(function(resolve) {
resolve(ret);
});
}
} else if (promise.status == REJECTED) {
var ret = onRejected(promise.value);
if(ret instanceof Promise) {
return ret;
} else {
return new Promise(function(resolve, reject) {
reject(ret);
});
}
}
return new Promise(function(resolve, reject) {
promise.resolver = onFulfilled;
promise.resolver_relsolve = resolve;
promise.rejecter = onRejected;
promise.rejecter_reject = reject;
});
}
测试
var p = new Promise(function(resolve, reject) {
console.log('before');
setTimeout(function() {
resolve(10);
}, 2000);
});
p.then(function() {
console.log('after', arguments);
}).then(function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(20)
}, 2000);
});
}).then(function() {
console.log(arguments);
});
输出
// 两秒
before
after [10]
// 两秒
[20]
keep learning