实现Promise中的静态方法:resolve/reject/race/all/any/allSettled
Promise.resolve = function (value) {
if (value && typeof value === "object" && value instanceof Promise) {
return value;
}
return new Promise((resolve) => {
resolve(value);
});
};
Promise.reject = function (value) {
return new Promise((resolve, reject) => {
reject(value);
});
};
// 只要p1、p2、p3之中有一个实例率先改变状态(不管是fulfilled还是rejected),p的状态就跟着改变
Promise.race = (list) => {
return new Promise((rs, rj) => {
list.forEach(p => Promise.resolve(p).then(rs).catch(rj));
})
}
// 只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled;
// 只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected
Promise.all = (list) => {
return new Promise((rs, rj) => {
const length = list.length;
if (length === 0) {
return rs([]);
}
let count = 0;
let result = [];
list.forEach((p, i) => {
Promise.resolve(p).then((value) => {
count += 1;
result[i] = value;
if (count === length) {
rs(result);
}
}).catch(rj);
})
})
}
// 只有p1、p2、p3的状态都变成rejected,p的状态才会变成rejected;
// 只要p1、p2、p3之中有一个被fulfilled,p的状态就变成fulfilled
Promise.any = (promises) => {
return new Promise((rs, rj) => {
const length = list.length;
if (length === 0) {
rj('All promises were rejected');
}
let count = 0;
list.forEach((p, i) => {
Promise.resolve(p).then(rs).catch((error) => {
count += 1;
if (count === length) {
rj('All promises were rejected');
}
});
})
})
};
// 只有p1、p2、p3都变状态(不管是fulfilled还是rejected),p的状态才跟着改变。
Promise.allSettled = (list) => {
return new Promise((rs, rj) => {
if (!Array.isArray(list)) {
return rj('Promise.allSettled accepts an array');
}
const length = list.length;
if (length === 0) {
rs([]);
}
let result = [];
let count = 0;
list.forEach((p, i) => {
Promise.resolve(p).then((value) => {
count++;
result[i] = {
status: 'fulfilled',
value
};
if (count === length) {
rs(result);
}
}).catch((value) => {
count++;
result[i] = {
status: 'rejected',
value
};
if (count === length) {
rs(result);
}
})
})
})
}