首页 > 解决方案 > 为每个内部执行并行承诺

问题描述

我正在尝试在 forEach 中执行一组承诺 A、B、C、D。这些承诺应该对所有列表项按顺序并行执行。我希望执行等到所有承诺都得到解决。但是一旦遇到 forEach 中的第一个 Promise,流程就会开始并行处理其他函数。在下面的代码片段中,列表中的所有 promise 都被解析后,应该触发 thirdCall。但是,它仍然不起作用

async function getList(value) {
  return someList;
}

async function processList(list) {
  try {
    await list.forEach(async (element) => {
      await A(element.firstProperty); // console jumps to thirdCall() while executing A,B,C,D in parallel
      await B(element.secondProperty);
      await C(element.thirdProperty);
      await D(element.fourthProperty);
    });
    return response;
  } catch (e) {
    throw (e);
  }
}

async function thirdCall() {
  try {
    let someresult = someProcessing(); // this should start execution ONLY AFTER processList() is done.
    await E(someresult);
    thirdCallResponse;
  } catch (error) {
    console.log(`error deleting policy ${error}`);
    throw error;
  }
}

async function processValue(value) {
  try {
    const list = await getList(value);
    await processList(list);
    await thirdCall(value);
  } catch (error) {
    console.log(error);
  }
}

processValue('someGuid');


标签: javascriptnode.jsasync-await

解决方案


推荐阅读