I was using map to handle loops, but I found out that it struggles when handling asynchronous requests. Map doesn't wait till the previous request end to start a new one, even when you use:
array.map(asyncdata=>{// Promise});
For this specific reason, I come back to for loops.
This is because you are returning an array of pending promises. If you want to fulfill these promises, you can use Promise.all. And if you want the result, you must await the resolution of Promise.all. Or you can also use .then.
In considering this comment I discovered one can use .reduce() to return promises in sequence (which I also thought cool enough to share):
functionrunPromiseInSequence(arr,input){returnarr.reduce((promiseChain,currentFunction)=>promiseChain.then(currentFunction),Promise.resolve(input))}// promise function 1functionp1(a){returnnewPromise((resolve,reject)=>{resolve(a*5)})}// promise function 2functionp2(a){returnnewPromise((resolve,reject)=>{resolve(a*2)})}// function 3 - will be wrapped in a resolved promise by .then()functionf3(a){returna*3}// promise function 4functionp4(a){returnnewPromise((resolve,reject)=>{resolve(a*4)})}constpromiseArr=[p1,p2,f3,p4]runPromiseInSequence(promiseArr,10).then(console.log)// 1200
Good thoughts, that's for leading me to that find.
but that was a very helpful post!
I really like using map. It syntax combined with the fact that it doesn't change the original array it's very handy. If they improve async I'll definitely switch back to map (:
I was using map to handle loops, but I found out that it struggles when handling asynchronous requests. Map doesn't wait till the previous request end to start a new one, even when you use:
For this specific reason, I come back to for loops.
This is because you are returning an array of pending promises. If you want to fulfill these promises, you can use
Promise.all
. And if you want the result, you mustawait
the resolution ofPromise.all
. Or you can also use.then
.In considering this comment I discovered one can use .reduce() to return promises in sequence (which I also thought cool enough to share):
Good thoughts, that's for leading me to that find.
yes for loop is the fastest among all the other methods. yes everything has the pro and cons we have to choose wisely what to use in which situation
absolutely!
but that was a very helpful post!
I really like using map. It syntax combined with the fact that it doesn't change the original array it's very handy. If they improve async I'll definitely switch back to map (:
thanks, buddy, I am also the map syntax lover. I can't imagine the React without the map
Hopefully, JS will add something like IAsyncEnumrable like C#, sometime soon.