当前位置:网站首页>面试会问的 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);
});
}
})
}
谢谢你看到这里, 祝福你面试顺利
边栏推荐
- Pytorch---使用Pytorch实现U-Net进行语义分割
- Thinkphp6 limit interface access frequency
- Unit testing classic three questions: what, why, and how?
- 汇编语言中的标志位:CF、PF、AF、ZF、SF、TF、IF、DF、OF
- Wechat applet JWT login issue token
- CorelDRAW graphics suite2022 free graphic design software
- Flag bits in assembly language: CF, PF, AF, ZF, SF, TF, if, DF, of
- Pytoch yolov5 runs bug solution from 0:
- Three years of experience in Android development interview (I regret that I didn't get n+1, Android bottom development tutorial
- C语言猜数字游戏
猜你喜欢
缓存一致性解决方案——改数据时如何保证缓存和数据库中数据的一致性
Thinkphp Kernel wo system source Commercial Open source multi - user + multi - Customer Service + SMS + email notification
Deep understanding of lambda expressions
Mysql表insert中文变?号的问题解决办法
深圳打造全球“鸿蒙欧拉之城”将加快培育生态,优秀项目最高资助 1000 万元
Leetcode merge sort linked list
June book news | 9 new books are listed, with a strong lineup and eyes closed!
Three years of experience in Android development interview (I regret that I didn't get n+1, Android bottom development tutorial
[source code analysis] NVIDIA hugectr, GPU version parameter server - (1)
win10 磁盘管理 压缩卷 无法启动问题
随机推荐
阿里云polkit pkexec 本地提权漏洞
Today's plan: February 15, 2022
[C language] basic learning notes
Sword finger offer II 006 Sort the sum of two numbers in the array
office_ Delete the last page of word (the seemingly blank page)
BGP experiment the next day
【c语言】动态规划---入门到起立
Design and implementation of general interface open platform - (44) log processing of API services
Shutdown procedure after 60
Mysql中常见的锁
cookie、session、tooken
Recyclerview add header
powershell_ View PowerShell function source code (environment variable / alias) / take function as parameter
Which insurance company has a better product of anti-cancer insurance?
June book news | 9 new books are listed, with a strong lineup and eyes closed!
There is no prompt for SQL in idea XML, and the dialect setting is useless.
Arbre binaire pour résoudre le problème (2)
C - derived classes and constructors
Okcc why is cloud call center better than traditional call center?
C language practice - number guessing game