使用Promise.all并行处理时未等待所有Promise解决的问题
问题分析与解决
你的核心问题是**Promise.all数组中的元素是未执行的async箭头函数,而非Promise实例**,导致这些函数根本没有被调用,自然不会生成对应的Promise,无法实现预期的并行处理。
错误原因
你在Promise.all里写的是(async () => await a())这类函数表达式,但没有执行它们(缺少()调用)。Promise.all会将非Promise类型的值直接视为已fulfilled的Promise,所以这些未执行的函数会被当作普通值处理,不会触发a()到e()的执行。
修正方案
方案1:调用async箭头函数
给每个箭头函数加上调用括号,让它们执行并返回Promise实例:
console.log("==PARALLEL with await Promise.all=="); parallel(); async function parallel() { await Promise.all([ (async () => await a())(), // 加上()调用函数 (async () => await b())(), (async () => await c())(), (async () => await d())(), (async () => await e())(), ]); } function a() { console.log("In function a "); return Promise.resolve(1); } function b() { console.log("In function b "); return Promise.resolve(2); } function c() { console.log("In function c "); return Promise.resolve(3); } function d() { console.log("In function d "); return Promise.resolve(4); } function e() { console.log("In function e "); return Promise.resolve(5); }
方案2:简化代码(更推荐)
因为a()到e()本身就直接返回Promise,完全不需要额外包一层async箭头函数,直接将函数调用传入Promise.all即可,代码更简洁高效:
console.log("==PARALLEL with await Promise.all=="); parallel(); async function parallel() { await Promise.all([ a(), b(), c(), d(), e(), ]); } // a-e函数保持不变 function a() { console.log("In function a "); return Promise.resolve(1); } function b() { console.log("In function b "); return Promise.resolve(2); } function c() { console.log("In function c "); return Promise.resolve(3); } function d() { console.log("In function d "); return Promise.resolve(4); } function e() { console.log("In function e "); return Promise.resolve(5); }
效果验证
修正后,a()到e()会被并行调用,控制台会输出所有函数内的日志,且Promise.all会等待所有Promise都fulfilled后再继续执行。
内容的提问来源于stack exchange,提问作者Michael36
相关产品推荐
相关产品推荐

