面试的笔试题中遇到过手写promise的题目,以下是参考了网上的文章,自己整理的一个简单的promise函数:
function Promise(executor) {
let self = this;
self.status = 'pending';
self.value = 'undefined';
self.reason = 'undefined';
function resolve(value) {
if(self.status === 'pending') {
self.status = 'resolve';
self.value = value;
}
}
function reject(reason) {
if(self.status === 'pending') {
self.status = 'reject'
self.reason = reason
}
}
try {
executor(resolve,reject)
} catch {
reject(e)
}
}
Promise.prototype.then = function (onFulfilled,onRejected) {
let self = this
if(self.status === 'resolve') {
onFulfilled(self.value)
} else {
onRejected(slef.reason)
}
}
module.exports = Promise
网友评论