【问题标题】:then block executed before promise resolves/reject (Promise.allSettled)然后在承诺解决/拒绝之前执行块(Promise.allSettled)
【发布时间】:2023-04-05 20:54:01
【问题描述】:

注意:问题在于没有在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}`);
  }
}

【问题讨论】:

标签: javascript typescript promise es6-promise


【解决方案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);

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 2023-03-26
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多