Promises can be really tricky to understand in Javascript. Should we use Promises or the combo async/await? It can be a tough choice.

But when it gets to doing functional programming, it can start to be confusing. What if your callback is dealing with asynchronous functions and you’d like to await them? How can you then deal with the return value of your Map callback? (Which will be a Promise as the callback is async)

Unfortunately, even if it’d make sense, the usage of await directly on the Map is not possible. Let’s get the following scenario:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

async function test() {
  const results = await array.map(async(item) => {
   // The setTimeout with await simulate a "heavy async function"
   await setTimeout(() => {}, 1000);
    return item;
  })

  console.log(results);
}
test()

#javascript #es6 #programming #developer

Await Array.Prototype.Map with ES6
2.35 GEEK