MST

星途 面试题库

面试题:JavaScript中如何使用Promise实现数组迭代的并发

假设有一个数组,数组中的每个元素都是一个需要异步处理的任务(例如通过`fetch`获取数据),请使用`Promise`实现这些任务的并发执行,最终返回所有任务的结果数组。要求代码实现清晰,并且处理可能出现的错误。
36.4万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
function executeTasksConcurrently(tasks) {
    return Promise.all(tasks.map(task => {
        return new Promise((resolve, reject) => {
            task()
              .then(result => {
                    resolve(result);
                })
              .catch(error => {
                    reject(error);
                });
        });
    }));
}

// 示例使用
const tasks = [
    () => fetch('https://example.com/api1').then(response => response.json()),
    () => fetch('https://example.com/api2').then(response => response.json()),
    () => fetch('https://example.com/api3').then(response => response.json())
];

executeTasksConcurrently(tasks)
  .then(results => {
        console.log(results);
    })
  .catch(error => {
        console.error('发生错误:', error);
    });