Promises in a loop

By Raúl on Jul 10, 2023
Image courtesy of unsplash

It’s interesting to see what happen to promises on for loops. Typically, this cause some over awaiting when it would be better to execute those Promises concurrently.

function holaPromise(message) {
 return new Promise(function(resolve, reject) {
// the function is executed automatically when the promise is constructed
// after 1 second signal that the job is done with the result "done"
setTimeout(() => {
            console.log("timeout :: ", message);
            return resolve("done");
        }, 1000);
    });
}

async function simple(message) {
    console.log(message);
}

async function mainMethod() {
  for(const run of[1, 2, 3]) {
    await holaPromise(run);
  }
}

async function parallel(){
  return Promise.allSettled([1,2,3].map((v)=>holaPromise(v)));
}


// Compare the sequential
mainMethod().then(result => console.log('finished :: ', result)).catch(error => console.error(error));

// And the concurrent
parallel().then(result => console.log('finished :: ', result)).catch(error => console.error(error));

2024. Personal website built with Astro & Streamline.