Promise相关面试常撕代码 all
Promise.myAll = function (iterators) {
const promises = Array.from(iterators);
const num = promises.length;
const resolvedList = new Array(num);
let resolveNum = 0;
return new Promise((resolve, reject) => {
promises.forEach((promsie, index) => {
Promise.resolve(promise)
.then(value => {
resolvedList[index] = value;
if (++resolveNum === num) {
resolve(resolvedList);
}
})
.catch(reject);
});
});
};
race
Promise.myRace = function (iterators) {
const promises = Array.from(iterators);
return new Promise((resolve, reject) => {
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then(resolve)
.catch(reject);
});
});
};
any
Promise.myAny = function (iterators) {
const promises = Array.from(iterators);
const num = promises.length;
const rejectedList = new Array(num);
let rejectedNum = 0;
return new Promise((resolve, reject) => {
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then(value => resolve(value))
.catch(error => {
rejectedList[index] = error;
if (++resolvedNum === num) {
reject(rejectedList);
}
})
})
})
}
allSettled
const formatSettledResult = (success, value) =>
success
? {status: 'fulfilled', value}
: {status: 'rejected', reason: value};
Promise.allSettled = function (iterators) {
const promises = Array.from(iterators);
const num = promises.length;
const settledList = new Array(num);
let settledNum = 0;
return new Promise((resolve, reject) => {
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then(value => {
settledList[index] = formatSettledResult(true, value);
if (++settledNum === num) {
resolve(settledList);
}
})
.catch(error => {
settledList[index] = formatSettledResult(false, error);
if (++settledNum === num) {
resolve(settledList);
}
})
})
})
}
finally
Promise.prototype.finally = function (fn) {
return this.then(
value => Promsie.resolve(fn()).then(() => value);
error => Promise.resolve(fn()).then(() => {
throw error;
})
)
}
推荐阅读
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- linux笔记|linux 常用命令汇总(面向面试)
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 面试|我经历的IT公司面试及离职感受(转)
- android-面试|我经历的IT公司面试及离职感受
- Java|一个月内面了30家企业,不断对比薪资,我从18K变成了38K
- vue|Vue面试常用详细总结
- java人生|35K 入职华为Java开发那天,我哭了(这 5 个月做的一切都值了)
- Android|年后备战金三银四(Android面试吃透这一篇就没有拿不到的offer......)
- java|后悔没有早点遇到它 , 直接从 12K 涨到了 30K