面试题答案
一键面试const asyncFunction = async (num) => {
// 模拟异步操作
return new Promise((resolve) => {
setTimeout(() => {
resolve(num * 2);
}, 1000);
});
};
const arr = [1, 2, 3, 4, 5];
const results = Promise.all(arr.map(async (num) => await asyncFunction(num)));
results.then((values) => {
console.log(values);
});
使用的函数方法及原理:
map
:map
方法用于创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。在这里,我们使用map
遍历数组arr
中的每个元素,并对每个元素调用asyncFunction
异步函数。由于asyncFunction
返回一个Promise
,map
遍历后得到的新数组中的每一项都是Promise
。Promise.all
:Promise.all
方法接收一个Promise
数组作为参数,当这个数组里的所有Promise
都成功时,Promise.all
返回的Promise
才会成功,并且其成功回调的参数是一个数组,包含了所有Promise
的成功结果。这里使用Promise.all
等待所有asyncFunction
异步操作完成,并获取它们的结果。这样就实现了并发调用数组中的每个元素作为参数传入异步函数,并获取所有异步操作的结果。