有时候就需要一个简单的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);
});