1

note: The issue was in not putting return on map so not related with Promise

I'm trying to to make multiple, independent api calls in parallel. Promise.allSettled(<promise array>) looked right for this scenario. This is my first try to ever use promise, so I might have made some obvious mistakes.

The issue: then was executed before promise resolve/reject. Things were printed in order indicated with circled numbers.

// 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
    You can use just `throw` instead of `return Promise.reject`. But notice you should always [throw errors, not strings](https://stackoverflow.com/q/11502052/1048572). Also avoid [`await`ing a `.then(…)` chain](https://stackoverflow.com/a/54387912/1048572)! Just do `const results = await Promise.allSettled(arrPromise);` – Bergi May 27 '21 at 10:53

1 Answers1

1

It's not related to Promise.allSettled:

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

arrPromise should be an array of promises, but isn't: you're not returning them from the map callback. Use

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

or

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

or just

const arrPromise = testInfo.map(startRun);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375