Search code examples
javascriptpromisees6-promisemap-function

How to combine a .map() with a promise?


I have an array and I need, for each element of this array, to fetch some data (dependent on the element) and add this data to the element in the array.

To set an example, I will simulate the fetch with a Promise (in real life, this will be the answer of a webservice):

let p = new Promise((resolve, reject) => resolve('x'))
let a = ['a', 'b']
a = a.map(x => p.then(y => x + y))
console.log(a)

What I expected is to have for the first element (a) p being called, and upon resolution the result added to a (giving ax). Same for b.

Ultimately I expected a new array ['ax', 'bx'].

What I get instead is an array of Promises

Being quite new to Promises (which I find in theory wonderful) I have a hard time understanding what went wrong here. Is it possible to combine .map() and asynchronous actions within?


Solution

  • I expected a new array ['ax', 'bx'], but what I get instead is an array of Promises

    This is exactly what Promise.all was made for. Of course it doesn't produce a plain array but rather a promise for it, but you cannot avoid that when you're doing anything asynchronous.

    const promises = a.map(x => p.then(y => x + y))
    Promise.all(promises).then(console.log, console.error)