Asycn Array Map Method
But async array map method return the promise object instead of modified value. So, you need to pass async map array to promise.all to give the same result as map method.
Async Array Map Syntax Be Like –
array.map( async function(currentValue, index, array), thisValue)
const numbers = [1, 3, 5];
In the second step, we create an function with name addOne and add async to it.
const addOne = async (num) => num + 1;
Now, create another variable numbersPlusOne, and assign the array return from the map method.
const numbersPlusOne = numbers.map(addOne);
Finally, we are checking the value numbersPlusOne using console log.
const numbers = [1, 3, 5]; const addOne = async (num) => num + 1; const numbersPlusOne = numbers.map(addOne); console.log(numbersPlusOne); // output => ?
Any idea what should be the output of above code snippet ?
Now, you know the answer is [Promise, Promise, Promise] but why doesn’t it should provide the array with [2, 4, 6]. Let me explain.
In short, the answer is [Promise, Promise, Promise] because the async function returns the promise object. That’s why each element converted a promise object.
If you want to get the same result as map method then you have pass the result array to Promise.all(array)
At last, That’s why we get an answer “[Promise, Promise, Promise]“.
Let me know in the comment section, what you think about it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – zero date can give get full year method
- JS Quiz – does set object really store duplicate object
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.