promise的简单实现
promise是面试中经常会问到的一个问题,也是一个不太好说明白的问题,前面我们已经实现了观察者模式,今天就来实现一个promise吧。这个promise写的非常简单但是却容易明白,面试问到这样的问题就不难讲清楚了。
// promise
function Promise (handler) {
this.success = [];
this.fail = [];
this.status = 'pending';
// 绑定this,不然后续实话化调用resolve和reject时this会指向window
setTimeout(() => handler(this.resolve.bind(this), this.reject.bind(this)), 0);
}
Promise.prototype = {
// 不要携程箭头函数,不然this会指向window
resolve (data) {
this.status = 'success';
this.success.forEach(item => {
item(data);
})
},
reject (err) {
this.status = 'fail';
this.fail.forEach(item => {
item(err);
})
},
then (callback) {
this.success.push(callback);
// 返回this才能进行链式调用
return this;
},
catch (callback) {
this.fail.push(callback);
return this;
}
}
var p = new Promise2((resolve, reject) => {
if (Math.random() * 10 > 5) {
setTimeout(resolve({ message: '货准备好了' }), 1000)
} else {
reject({ message: '不能按时交付' });
}
})
p.then(function (data) {
console.log('我要去取货了,因为' + data.message);
}).catch(function (err) {
console.log('我的货物取不到了,因为' + err.message);
})

浙公网安备 33010602011771号