I am faced with a challenge where I have an array and for each element in the array, I need to retrieve some data based on that element and then append it to the respective element in the array.
For illustration purposes, I will create a simulated fetch
operation using a Promise (in reality, this would involve fetching data from a web service):
let p = new Promise((resolve, reject) => resolve('x'))
let a = ['a', 'b']
a = a.map(x => p.then(y => x + y))
console.log(a)
I expected that when performing the above operation, the first element (a
) would invoke the Promise p
, and upon resolution, the result would be added to a
(resulting in ax
). The same process would be repeated for b
.
Ultimately, my expectation was to obtain a new array as ['ax', 'bx']
.
However, instead of getting the desired outcome, I ended up with an array of Promises.
Given my limited experience with Promises (despite finding them conceptually fascinating), I am struggling to comprehend what might have gone wrong. Can .map()
be effectively combined with asynchronous tasks?