DEV Community

Discussion on: Don’t use for loop for JavaScript Arrays

Collapse
 
gstvds profile image
Gustavo da Silva

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(async data => {
  // Promise
});
Enter fullscreen mode Exit fullscreen mode

For this specific reason, I come back to for loops.

Collapse
 
aminnairi profile image
Amin • Edited

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.

function sleep(seconds: number) {
    return new Promise(function(resolve) {
        setTimeout(resolve, 1000 * seconds);
    });
}

function increment(input: number) {
    return input + 1;
}

async function main() {
    const nums = await Promise.all([1, 2, 3, 4, 5].map(async (num) => {
        await sleep(1);

        return increment(num);
    }));

    console.log(nums);
    // [ 2, 3, 4, 5, 6 ]
}

main();
Collapse
 
dsbarnes profile image
dsbarnes

In considering this comment I discovered one can use .reduce() to return promises in sequence (which I also thought cool enough to share):

function runPromiseInSequence(arr, input) {
  return arr.reduce(
    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
    Promise.resolve(input)
  )
}

// promise function 1
function p1(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 5)
  })
}

// promise function 2
function p2(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 2)
  })
}

// function 3  - will be wrapped in a resolved promise by .then()
function f3(a) {
 return a * 3
}

// promise function 4
function p4(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 4)
  })
}

const promiseArr = [p1, p2, f3, p4]
runPromiseInSequence(promiseArr, 10)
  .then(console.log)   // 1200
Enter fullscreen mode Exit fullscreen mode

Good thoughts, that's for leading me to that find.

Collapse
 
sharmakushal profile image
Kushal sharma

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

Collapse
 
gstvds profile image
Gustavo da Silva

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 (:

Thread Thread
 
sharmakushal profile image
Kushal sharma

thanks, buddy, I am also the map syntax lover. I can't imagine the React without the map

Collapse
 
mccshreyas profile image
Shreyas Jejurkar

Hopefully, JS will add something like IAsyncEnumrable like C#, sometime soon.

Some comments have been hidden by the post's author - find out more