当前位置:网站首页>面试会问的 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);
});
}
})
}

谢谢你看到这里, 祝福你面试顺利
边栏推荐
- Pytoch --- use pytoch to predict birds
- powershell_ View PowerShell function source code (environment variable / alias) / take function as parameter
- Design and implementation of general interface open platform - (44) log processing of API services
- Let genuine SMS pressure measurement open source code
- idea自動導包和自動删包設置
- Markdown edit syntax
- Yolov5 network modification tutorial (modify the backbone to efficientnet, mobilenet3, regnet, etc.)
- Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知
- Typescript practice for SAP ui5
- A summary of common interview questions in 2022, including 25 technology stacks, has helped me successfully get an offer from Tencent
猜你喜欢

Cache consistency solution - how to ensure the consistency between the cache and the data in the database when changing data

CorelDRAW graphics suite2022 free graphic design software

Websites that it people often visit

Force buckle 540 A single element in an ordered array

Mysql database learning

Deeply understand the concepts of synchronization and asynchrony, blocking and non blocking, parallel and serial

Lei Jun wrote a blog when he was a programmer. It's awesome

Pytorch---使用Pytorch进行图像定位

Let genuine SMS pressure measurement open source code

Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知
随机推荐
Pytorch-Yolov5從0運行Bug解决:
Yyds dry inventory compiler and compiler tools
Pytorch---使用Pytorch实现U-Net进行语义分割
Thinkphp6 limit interface access frequency
Sword finger offer II 006 Sort the sum of two numbers in the array
Leetcode- insert and sort the linked list
Ognl和EL表达式以及内存马的安全研究
Target free or target specific: a simple and effective zero sample position detection comparative learning method
BGP experiment the next day
Websites that it people often visit
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
office_ Delete the last page of word (the seemingly blank page)
【c语言】基础篇学习笔记
What are the rules and trading hours of agricultural futures contracts? How much is the handling fee deposit?
Feature Engineering: summary of common feature transformation methods
The solution to the complexity brought by lambda expression
Landing guide for "prohibit using select * as query field list"
Cache consistency solution - how to ensure the consistency between the cache and the data in the database when changing data
Geotrust OV Multi - Domain Domain SSL Certificate rmb2100 per year contains several Domain names?
Which insurance company has a better product of anti-cancer insurance?