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?