JavaScript : await inline with for statement
2025-09-21
Today, i learnt another cool trick — to use await inline with for statement
for await (const res of somePromiseArray) {}
Scenario: I want to print the outcomes of resolved promises, which are passed in as argument, as array of Promise.
// Input const somePromiseArray = [ new Promise((resolve) => setTimeout(() => resolve('Job 1'), 2000)), // Job 1 finished after 2s new Promise((resolve) => setTimeout(() => resolve('Job 2'), 1000)), // Job 2 finished after 1s new Promise((resolve) => setTimeout(() => resolve('Job 3'), 300)), // Job 3 finished after 0.3s ]
// says i want to print the result, my first try would be const naivePrint = (somePromiseArray) => { console.log("start") somePromiseArray.forEach(promise => { promise.then(res => console.log(res)) }) console.log("end") } naivePrint() /* Actual: start end Job 3 Job 2 Job 1 */
Above is how i would first try, forgetting that the input array are promise array.
The print is not in order of array index, but in order of who resolving promise earlier.
This is unlikely what most developers want, we prefer “in index order”, so we expecting:
/* Expecting: start Job 1 Job 2 Job 3 end */
So, to solve the issue:
My favorite Approach #1: async/await , with for loop
// Approach #1: async/await, with for loop // make the function a promise with async // add await inside for-loop, so it would wait till the promise is resolved, // before execute next promise in array const print = async (somePromiseArray) => { console.log("start") for (const promise of somePromiseArray) { const res = await promise console.log(res) } console.log("end") } print() /* start Job 1 Job 2 Job 3 end */
My favorite Approach #2: async/await , with for loop(variant)
// Approach #2: async/await , with for loop(variant) // similar to approach #1, but the await is in-line with for statement // reduce 1 line :) const print = async (somePromiseArray) => { console.log("start") for await (const res of somePromiseArray) { // inline await with for-statement console.log(res) } console.log("end") } print() /* start Job 1 Job 2 Job 3 end */
My favorite Approach #3: async/await , Promise.all()
// Approach #3: async/await , Promise.all() // if you like functional-programming style const print = async (somePromiseArray) => { console.log("start") const resultArray = await Promise.all(somePromiseArray) resultArray.forEach(res => console.log(res)) console.log("end") } print() /* start Job 1 Job 2 Job 3 end */
So, which approach you like, and what are the differences between each approach ?
Comment below and let me know
Also published at linkedin article: