1

I am trying to execute multiple promises using async with map:

const testAsyncFunction = async function testAsyncFunction() {
  const array = ["var1", "var2"];
  const promises = array.map(
    (variable) =>
      async function () {
        // This doesn't get logged
        console.log(
          " ~ file: coursesServices.js ~ line 853 ~ testAsyncFunction ~ variable",
          variable
        );
        return variable + "TEST";
      }
  );
  const promises_results = await Promise.all(promises);
  // This gets logged
  console.log(
    " ~ file: coursesServices.js ~ line 861 ~ testAsyncFunction ~ promises_results",
    promises_results
  );
};
testAsyncFunction();

The problem here is that the code inside the map function never gets executed.

This is what gets logged in the console:

 ~ file: coursesServices.js ~ line 861 ~ testAsyncFunction ~ promises_results [ [AsyncFunction (anonymous)], [AsyncFunction (anonymous)] ]

I don't see what I'm doing wrong exactly. But, I have a feeling that Promise.all wouldn't work on an array of async functions.

AG_HIHI
  • 1,705
  • 5
  • 27
  • 69
  • 3
    A `function` is not a `Promise`. Either return an explicit `Promise` in the `.map()` callback (`.map(value => new Promise(...)`) or execute the anonymous function in the callback and return their return value (`.map(value => (async function() { ... })())`). – Andreas Jun 17 '21 at 12:14
  • 2
    @Andreas or just use an async callback in the `.map()` instead of returning an async function: `.map(async (value) => { /* ... */ })` – VLAZ Jun 17 '21 at 12:18

1 Answers1

1

You should use new promise inside the map. otherwise the promise.all does't not care about the map

(async() => {
  const arr = [1, 2, 3]
  const res = arr.map((a) => {
    return new Promise((resolve) => {
      setTimeout(() => {  //async call
        resolve(a + 'finished')
      }, 1000)
    })
  })
  console.log(await Promise.all(res))
})()
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • [No need for explicit `new Promise()`](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) because [the `.map()` already has an async function](https://stackoverflow.com/questions/43036229/is-it-an-anti-pattern-to-use-async-await-inside-of-a-new-promise-constructor). – VLAZ Jun 17 '21 at 12:54