然后在承诺解决/拒绝之前执行块(Promise.allSettled)

时间:2021-05-27 10:36:32

标签: javascript typescript promise es6-promise

注意:问题在于没有将回报放在 map 上,因此与 Promise

无关

我正在尝试并行进行多个独立的 api 调用。 Promise.allSettled(<promise array>) 看起来很适合这种情况。这是我第一次尝试使用 promise,所以我可能犯了一些明显的错误。

问题:然后在承诺解决/拒绝之前执行。 事情是按带圈数字指示的顺序打印的。

// typescript version: 3.9.9
async function startTest(testInfo: someObjectType[]): Promise<string> {
  const arrPromise = testInfo.map((info) => { startRun(info) });
  console.log(arrPromise); // ① prints [undefined, ..., undefined]

  (Promise as any)
    .allSettled(arrPromise)
    .then(async (results: any) => { // it was omitted but await was used in then block
      console.log('[resolved all]'); // ②
      for (const result of results) {
        if (result.status == 'fulfilled') {
          console.log(`resolve ${result.value}`); // ③ undefined
        }
      }
  });
  return 'some string data';
}

async function startRun(info: someObjectType): Promise<testResult|string> {
  try {
    const resp = await httpRequestHandler.post(`<request url>`, {request header});
    if (resp.statusCode == 200) return 'some test result object'; 
  } catch (ex) {
    console.log(`[failed]=${info.testName}`); // ④
    return Promise.reject(`${info.testName}: ${ex}`);
  }
}

1 个答案:

答案 0 :(得分:1)

它与Promise.allSettled无关:

<块引用>
const arrPromise = testInfo.map((info) => { startRun(info) });
console.log(arrPromise); // ① prints [undefined, ..., undefined]

arrPromise 应该是一个 promise 数组,但不是:您不会从 map 回调中返回它们。使用

const arrPromise = testInfo.map((info) => { return startRun(info) });
//                                          ^^^^^^

const arrPromise = testInfo.map(info => startRun(info));

或者只是

const arrPromise = testInfo.map(startRun);