实现Promise功能
代码如下:
var selfPromise = (function() {
function Promise(fn) {
this.callbacks = [];
fn(this.resolve.bind(this),this.reject.bind(this));
}
Promise.prototype = {
constructor: Promise,
resolve: function(result) {
this.complete('resolve', result);
},
reject: function(result) {
this.complete('reject', result);
},
complete: function(type, result) {
while (this.callbacks[0]) {
this.callbacks.shift()[type](result);
}
},
then: function(successHandler, failedHandler) {
this.callbacks.push({
resolve: successHandler|| function(){},
reject: failedHandler|| function(){}
});
return this;
}
};
return Promise;
})();
示例:
var promise = new selfPromise(function(resolve,reject){
setTimeout(function(){
resolve('object');
},1000);
});
promise.then(function(res){
console.log(res);
});
//一秒后输出 object