手写Promise

原文地址: https://segmentfault.com/a/1190000018260324

(function(){
const PENDING = 'pending';
const RESOLVED = 'fullfilled';
const REJECTED = 'rejected';
function MyPromise(fn) {
const that = this
that.state = PENDING
that.value = null
that.resolvedCallbacks = [];
that.rejectedCallbacks = [];
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}
function resolve(value) {
if (that.state === PENDING) {
that.state = RESOLVED
that.value = value // 返回的值
that.resolvedCallbacks.map(cb => cb(that.value))
}
}

function reject(value) {
if (that.state === PENDING) {
that.state = REJECTED
that.value = value
that.rejectedCallbacks.map(cb => cb(that.value))
}
}
}
MyPromise.prototype.then = function(onFulfilled) {
const that = this
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
if (that.state === PENDING) {
that.resolvedCallbacks.push(onFulfilled)
}
}
MyPromise.prototype.catch = function(onRejected) {
const that = this
onRejected = typeof onRejected === 'function'? onRejected: r => { throw r;}
if (that.state === PENDING) {
that.rejectedCallbacks.push(onRejected)
}
}
window.MyPromise = MyPromise;
})();
var p1 = new MyPromise((resolve,reject) => {
setTimeout(() => {
resolve(10); // 或resolve
},1000);
});
console.log(p1);
p1.then((data)=>{
console.log(my final data is: ${data});
});

你可能感兴趣的:(手写Promise)