Why did await not wait?
forEach ignores the promises returned by async callbacks. Awaiting its undefined result does not wait for your uploads.
Use for...of for ordered work or Promise.all for a small independent group. Catch failures; Promise.all does not cancel other work. Limit concurrency for large lists.
Understand it. Then fix it.
Three promises. None returned to await.
Each async call returns a promise: an object for a future result. But forEach ignores those promises and returns undefined. Your outer await gets undefined, not the uploads.
Need an order? Wait after each file.
Right. To upload one file at a time, use for of. Await pauses this async function until each upload finishes. Only then does the next one start.
for (const file of files) {
await upload(file);
}
show("Upload complete");Independent files? Wait for the group.
For these three independent files, map collects their promises. Promise all waits for every upload to succeed. Then we show the message.
await Promise.all(
files.map(file => upload(file))
);
show("Upload complete");Failure is not completion.
Catch errors before showing success. Promise all does not cancel other uploads if one fails. For a large list, limit how many uploads run at once.
try {
await uploadAll(files);
show("Upload complete");
} catch {
show("Upload failed");
}Code blocks are teaching excerpts. Keep the surrounding error handling and application requirements.
Save the code excerpts ↓Read the full transcript
Why does my JavaScript say upload complete when all three files are still uploading? I used await. Each async call returns a promise: an object for a future result. But forEach ignores those promises and returns undefined. Your outer await gets undefined, not the uploads. So the uploads keep going, but my success message does not wait for them? Right. To upload one file at a time, use for of. Await pauses this async function until each upload finishes. Only then does the next one start. For these three independent files, map collects their promises. Promise all waits for every upload to succeed. Then we show the message. Catch errors before showing success. Promise all does not cancel other uploads if one fails. For a large list, limit how many uploads run at once. Nothing uploaded. Everything reported. My code is ready to become a manager.