Why Does My JavaScript Function Finish Before Its async forEach Callbacks?

Asked 4 days ago 45 views

0

I have a saveRow() helper that returns a promise for a database write. I want saveAll() to finish only after every row has been saved, but the completion message appears while writes are still running.

async function saveAll(rows) {
    // Attempt to wait for all row-saving callbacks.
    await rows.forEach(async (row) => {
        // Each callback waits for its own database write.
        await saveRow(row);
    });

    console.log("All rows saved");
}

// The caller also needs to wait for the writes.
await saveAll(rows);

This runs in a JavaScript module, and both rows and saveRow are defined elsewhere. The database helper behaves as expected when I await a single write.

What am I misunderstanding about async callbacks in forEach? Does the outer await wait for anything here?

For this import, rows should be saved in order, and a failed write should stop the remaining rows. I’m looking for the appropriate loop structure for those requirements, rather than simply starting every write at once.

0 Answers


Write Your Answer