JavaScript异步任务未执行问题排查及修复方案
问题分析与修复方案
问题根源
你当前的代码只是把异步函数定义塞进了tasks数组,而不是执行这些函数得到的Promise实例。Promise.allSettled()需要接收一组Promise对象才能触发异步任务执行,所以你的那些async函数根本没被调用,自然不会执行里面的逻辑。
另外代码里还有个语法错误:console.log("log") --> dose not run !!! 这里的-->是无效语法,会导致代码报错,要改成注释符号//。
修复方案
把每个task函数调用后再push进数组,这样tasks里就会是一个个Promise对象,Promise.allSettled()才能正确触发所有异步任务。
修正后的完整代码:
const tasks = []; for (const space of results.data.querySpace) { let rows = []; // check rows if (space.rows) { // check component is enable or not space.rows = space.rows.filter( (item) => item.component.is_enable === true ); rows = space.rows; } for (const row of rows) { // iterate over the components and fetch their list fields const component = row.component; let task; if (component.__typename === "Program_Component") { task = async () => { component.episodes = await getPrograms( args.Copyright, component.tag_name, graphql ); }; } else if (component.__typename === "Episode_Component") { task = async () => { console.log("log"); // 修复语法错误,替换无效的-->为注释 component.episodes = await getEpisodes( args.Copyright, component.tag_name, graphql ); }; } else if (component.__typename === "FullscreenBanner_Component") { task = async () => { component.episodes = await getEpisodes( args.Copyright, component.tag_name, graphql ); }; } // 关键修复:调用task函数,将返回的Promise推入数组 tasks.push(task()); } } const test = await Promise.allSettled(tasks); console.log(test); return results.data.querySpace[0];
额外说明
Promise.allSettled()会等待所有Promise完成(不管成功还是失败),适合你这种需要确保所有字段填充任务都执行完的场景。- 因为你是直接修改
component对象的episodes属性,所以当异步任务完成后,原始的results.data.querySpace里的组件数据会被自动更新,最后返回的results.data.querySpace[0]会包含填充后的字段。
内容的提问来源于stack exchange,提问作者mahdi aghasi
相关产品推荐
相关产品推荐

