Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 9 of 10 · Promises and Async/Await
Interview question

Can you use await inside a regular for loop and a forEach loop? What's the difference? क्या आप regular for loop और forEach loop में await use कर सकते हैं? क्या अंतर है?

Answer

await works correctly inside a regular for loop because the loop itself is inside an async function's synchronous flow. It does NOT work as expected inside Array.forEach() because the callback passed to forEach is not awaited by forEach itself.

function delay(value, ms) {
    return new Promise(resolve => setTimeout(() => resolve(value), ms));
}

// CORRECT - regular for loop, awaits sequentially
async function withForLoop() {
    const items = [1, 2, 3];
    for (const item of items) {
        const result = await delay(item, 500);
        console.log(result); // 1, 2, 3 in order, with real delay between
    }
    console.log('Loop complete');
}

// INCORRECT - forEach does not wait for the async callback
async function withForEach() {
    const items = [1, 2, 3];
    items.forEach(async (item) => {
        const result = await delay(item, 500);
        console.log(result); // Fires all together, order not guaranteed to complete first
    });
    console.log('Loop complete'); // This logs IMMEDIATELY, before any delay finishes
}

// CORRECT alternative to run in parallel: map + Promise.all
async function withMapAndAll() {
    const items = [1, 2, 3];
    const promises = items.map(item => delay(item, 500));
    const results = await Promise.all(promises);
    console.log(results); // [1, 2, 3] after ~500ms total, not 1500ms
}

// for...of DOES respect await because it's a normal loop construct,
// not a higher-order function taking a callback

await regular for loop में सही से काम करता है क्योंकि loop खुद async function के synchronous flow में है। Array.forEach() में यह expected तरीके से काम नहीं करता क्योंकि forEach callback को await नहीं करता।

function delay(value, ms) {
    return new Promise(resolve => setTimeout(() => resolve(value), ms));
}

// सही - regular for loop
async function withForLoop() {
    const items = [1, 2, 3];
    for (const item of items) {
        const result = await delay(item, 500);
        console.log(result); // क्रम में, delay के साथ
    }
    console.log('पूरा हुआ');
}

// गलत - forEach async callback को await नहीं करता
async function withForEach() {
    const items = [1, 2, 3];
    items.forEach(async (item) => {
        const result = await delay(item, 500);
        console.log(result);
    });
    console.log('पूरा हुआ'); // यह तुरंत चलता है, delay से पहले
}

// सही alternative: map + Promise.all
async function withMapAndAll() {
    const items = [1, 2, 3];
    const promises = items.map(item => delay(item, 500));
    const results = await Promise.all(promises);
    console.log(results); // [1, 2, 3] ~500ms में

Was this answer clear?