Why Does My JavaScript forEach Finish Before the Awaited Saves Complete?

Asked 44 minutes ago 3 views

0

I am saving a list of edited records, then showing a success message. Each call to saveRecord() returns a promise that resolves after the server confirms the write. However, the message appears while requests are still running.

async function saveAll(records) {
    // Attempt to wait for each server write inside the callback.
    records.forEach(async (record) => {
        await saveRecord(record);
    });

    // This should appear only after every write succeeds.
    console.log("All records saved");
}

// The caller also needs to know when the whole batch is finished.
await saveAll(editedRecords);

I thought making the callback async and awaiting saveRecord() would keep saveAll() pending. What am I misunderstanding about async callbacks in forEach?

Some batches contain independent records, but others must be saved in order. How should I choose between sequential and concurrent promise execution, and where should errors be caught so a failed write does not leave the caller believing the batch succeeded?

0 Answers


Write Your Answer