(function () {
const PENDING = 'pending';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';
// 1.定义三个状态用来标识一个Promise的异步任务进行到何种程度了
function MyPromise(fn) {
// 2.MyPromise 中的参数 fn 是需要用户传入的自定义函数(该函数需要接收两个参数resolve和reject )。
// 3.MyPromise 中的内部还有两个函数 resolve 和 reject,其中 resolve 表示用户的异步任务成功时应该调用的函数,reject 表示用户的异步任务失败时该调用的函数。
const that = this;
that.state = PENDING;
// 4.初始时状态为执行中,即pending
that.resolvedCallbackArray = [];
that.rejectedCallbackArray = [];
// 5.为了then的链式调用,将两个回调函数用函数数组的形式表示
function resolve(value) {
that.state = RESOLVED;
// 6.resolve被调用时修改状态
that.resolvedCallbackArray.forEach(cbFn => cbFn(value));
// // 7.遍历用户的回调函数,告知结果
}
function reject(value) {
that.state = REJECTED;
// reject被调用时修改状态
that.rejectedCallbackArray.forEach(cbFn => cbFn(value));
// // 遍历用户的回调函数,告知结果
}
fn(resolve, reject);
}
MyPromise.prototype.then = function(onFulfilled, onRejected) {
// 8.对参数进行校验,状态进行判断等,以 then为例,判断用户传入的参数不是函数
if(typeof onRejected !== 'function') {
onRejected = v => v;
}
if(typeof onFulfilled !== 'function') {
onFulfilled = v => { throw r };
}
const that = this;
if (that.state === PENDING) {
that.resolvedCallbacks.push(onFulfilled)
that.rejectedCallbacks.push(onRejected)
}
if (that.state === RESOLVED) {
onFulfilled(that.value)
}
if (that.state === REJECTED) {
onRejected(that.value)
}
}
new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('你又看到我啦~');
}, 2000)
}).then(value => {
console.log('第一次', value);
}).then(value => {
console.log('第二次', value);
});
})();
promise.all:成功的时候返回的是一个结果数组,而失败则返回最先被reject失败状态的值。
let p1 = new Promise((resolve, reject) => {
resolve('成功了')
})
let p2 = new Promise((resolve, reject) => {
resolve('success')
})
let p3 = Promse.reject('失败')
Promise.all([p1, p2]).then((result) => {
console.log(result) //['成功了', 'success']
}).catch((error) => {
console.log(error)
})
Promise.all([p1,p3,p2]).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error) // 失败了,打出 '失败'
})
Promise.race([p1, p2, p3])里面哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
},1000)
})
let p2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject('failed')
}, 500)
})
Promise.race([p1, p2]).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error) // 打开的是 'failed'
})