有時候就需要一個簡單的Promise撐場面,能用就行。
——真不行的時候咱再使用完整的實現唄。
實現的方法
1.new Promise(fn),創建一個新的Promise對象並傳入第一個執行方法。
2.resolve。成功的執行方法
3.reject。失敗的執行方法
4.catch。失敗的捕獲。
5.then。鏈式調用下一步。
原理
內部使用一個數組報錯需要執行的所有方法,使用then來添加新的方法。舊的方法執行完畢之後檢測數組,如果有新的就執行。
class Promise {
result: any;
callbacks = [];
failbacks = [];
constructor(fn) {
fn(this.resolve.bind(this), this.reject.bind(this));
}
resolve(res) {
if (this.callbacks.length > 0) this.callbacks.shift()(res, this.resolve.bind(this), this.reject.bind(this));
}
reject(res) {
this.callbacks = [];
if (this.failbacks.length > 0) this.failbacks.shift()(res, this.resolve.bind(this), this.reject.bind(this));
}
catch(fn) {
this.failbacks.push(fn);
}
then(fn) {
this.callbacks.push(fn);
return this;
}
}
調用示例:
var a=new Promise(function(resolve,reject){
setTimeout(function(){
resolve("成功");
},1000);
}).then(function(result,resolve,reject){
console.log(result)
reject("失敗")
}).catch(function(err){
console.log(err);
});