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.

2
  • 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() { ... })())). Commented Jun 17, 2021 at 12:14
  • 2
    @Andreas or just use an async callback in the .map() instead of returning an async function: .map(async (value) => { /* ... */ }) Commented Jun 17, 2021 at 12:18

1 Answer 1

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))
})()

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.