当前位置:网站首页>面试会问的 Promise.all()
面试会问的 Promise.all()
2022-07-02 04:35:00 【庇耳拉海莱】
Promise.all()
来看这个的应该都在面试吧~~~
Promise.all()
接收一组可迭代的 Promise
作为输入, 返回一个新的 Promise
对象, 其 resolve
回调的结果是输入的所有 Promise
的结果组成的数组.
如果输入的参数为空的可迭代对象, 或者所有输入的 Promise
都变成已完成状态, 那么返回的 Promise
也会变成已完成状态.
const promise1 = new Promise(resolve => {
setTimeout(() => {
resolve('');
}, 1000);
});
const promise2 = Promise.resolve(2);
const promise3 = 1;
Promise.all([promise1, promise2, promise3])
.then((result) => {
console.log('result is', result);
});
// 空的可迭代对象
Promise.all(new Set())
.then(result => {
console.log('new Set() result is', result);
});
虽然 promise1
最后才变成已完成状态, 但是在返回的结果中, 它仍然是第一个. 返回结果中的位置和其完成先后没关系, 和其在传入 all()
的位置有关系
不过一旦输入的任何 Promise
对象变成 rejected
或者输入的参数非可迭代对象(比如 null
或者 number
类型),那么返回的 Promise
立即 reject
, 并且 reject
回调的结果是第一个 reject
的信息或者报错信息.
const promise4 = new Promise(resolve => {
setTimeout(() => {
resolve(100);
}, 10000);
})
const promise5 = Promise.reject(200);
Promise.all([promise4, promise5])
.then(result => {
console.log('我不会执行的');
})
.catch(err => {
console.log('糟糕, ', err)
})
输入
Promise.all()
接收的是可迭代对象, 而不仅仅是数组, 数组虽然是可迭代对象, 但是 set
, string
等都属于可迭代对象. 因此 Promise.all('asd')
会输出什么呢?
哈哈, 这是因为 asd
字符串类型可迭代的. 如果我们组成可迭代对象的数据(a
, s
, d
)不是 Promise
对象, 就会被 resolve
变成已完成状态.
手写 Promise.all
面试中问到最多的就是被手写 Promise.all
实现
- 首先: 判断传入的参数是否为可迭代对象, 关于可迭代对象判断, 请看MDN这里;
- 其次, 如果是可迭代对象, 判断是否为空,
string
和数组
通过length
属性判断,Set
和Map
通过size
属性判断; - 创建两个变量, 分别使用
resolvedPromiseCount
和resolvedPromiseResult
用来记录已经完成的Promise
对象的数量和结果; - 使用
Promise.resolve()
处理可迭代对象中每个值, 如果这个值刚好是Promise
对象,resolve
就会原封不动地将这个对象返回; 如果这个值非Promise
对象, 就会创建一个resolve
这个值的Promise
对象.- 在
catch
方法中直接reject
; - 在
then
方法中增加resolvedPromiseCount
的值并将已完成的Promise
对象的结果保存在数组resolvedPromiseResult
的对应位置. 如果resolvedPromiseCount
刚好等于length
调用resolve
返回.
- 在
Promise.myAll = function (iterable) {
return new Promise((resolve, reject) => {
if (typeof iterable[Symbol.iterator] !== 'function') {
reject(new Error('参数必须是可迭代类型对象'));
}
let length = iterable.length || iterable.size;
if (length === 0) {
resolve([]);
}
let resolvedPromiseCount = 0;
let resolvedPromiseResult = [...' '.repeat(iterable.length)]
let i = 0;
for (let item of iterable) {
Promise.resolve(item)
.then(result => {
resolvedPromiseCount++;
resolvedPromiseResult[i++] = result;
if (resolvedPromiseCount === length) {
resolve(resolvedPromiseResult);
}
})
.catch(err => {
reject(err);
});
}
})
}
谢谢你看到这里, 祝福你面试顺利
边栏推荐
- geotrust ov多域名ssl證書一年兩千一百元包含幾個域名?
- 第十六周作业
- LeetCode-归并排序链表
- What are the rules and trading hours of agricultural futures contracts? How much is the handling fee deposit?
- Play with concurrency: draw a thread state transition diagram
- IDEA xml中sql没提示,且方言设置没用。
- Leetcode- insert and sort the linked list
- Actual combat | use composite material 3 in application
- 【毕业季·进击的技术er】年少有梦,何惧彷徨
- Www 2022 | rethinking the knowledge map completion of graph convolution network
猜你喜欢
Mysql表insert中文变?号的问题解决办法
Its appearance makes competitors tremble. Interpretation of Sony vision-s 02 products
LeetCode-对链表进行插入排序
Deep understanding of lambda expressions
Playing with concurrency: what are the ways of communication between threads?
Unit testing classic three questions: what, why, and how?
Www2022 | know your way back: self training method of graph neural network under distribution and migration
LeetCode-归并排序链表
Yyds dry inventory compiler and compiler tools
How much can a job hopping increase? Today, I saw the ceiling of job hopping.
随机推荐
Pytorch yolov5 exécute la résolution de bogues à partir de 0:
Yyds dry inventory compiler and compiler tools
Major domestic quantitative trading platforms
Lei Jun wrote a blog when he was a programmer. It's awesome
CorelDRAW graphics suite2022 free graphic design software
The confusion I encountered when learning stm32
powershell_ View PowerShell function source code (environment variable / alias) / take function as parameter
Pytorch---使用Pytorch实现U-Net进行语义分割
Yolov5 network modification tutorial (modify the backbone to efficientnet, mobilenet3, regnet, etc.)
unable to execute xxx. SH: operation not permitted
LxC limits the number of CPUs
CY7C68013A之keil编译代码
万卷共知,一书一页总关情,TVP读书会带你突围阅读迷障!
Play with concurrency: what's the use of interruptedexception?
[JS -- map string]
Ten thousand volumes are known to all, and one page of a book is always relevant. TVP reading club will take you through the reading puzzle!
geotrust ov多域名ssl证书一年两千一百元包含几个域名?
How to solve the problem that objects cannot be deleted in Editor Mode
The solution to the complexity brought by lambda expression
Shenzhen will speed up the cultivation of ecology to build a global "Hongmeng Oula city", with a maximum subsidy of 10million yuan for excellent projects