Does “for…of” loop wait for async awaits in JavaScript?


In JavaScript, a for...of (or for...let or for...const) loop does not automatically wait for await statements inside the loop. The loop will run to completion without waiting for the asynchronous operations to resolve.

const fetchData = async (id) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(`Data for ${id}`), 1000);
  });
};

const processItems = async () => {
  const items = [1, 2, 3];

  for (const item of items) {
    console.log(`Processing ${item}`);
    await fetchData(item).then((data) => console.log(data));
  }
  console.log("Done!");
};

processItems();

How it works:
  1. Await Behavior: In the example, the await fetchData(item) ensures the code inside the loop waits for the asynchronous operation to complete before moving to the next iteration.
  2. Synchronous Execution of the Loop Logic: The await pauses execution of the loop body, but the loop’s iterations are still processed sequentially.
Key Points:
  • for...of with await: If you include await inside a loop, it will wait for each asynchronous operation before proceeding to the next iteration.
  • Concurrency with Promise.all: To run all asynchronous operations in parallel and wait for them to complete, you can use Promise.all.

Sequential Example (for...of with await):
const processItemsSequentially = async (items) => {
  for (const item of items) {
    await fetchData(item); // Waits for each promise before moving to the next
  }
};
Parallel Processing Using Promise.all
  • Explanation of running promises concurrently to optimize performance.
  • Example: Processing a batch of asynchronous tasks in parallel.
  • Discussion of scenarios where Promise.all is beneficial and when it might not be suitable (e.g., dependency between tasks).
Parallel Example (Promise.all):
const processItemsInParallel = async (items) => {
  const results = await Promise.all(items.map((item) => fetchData(item)));
  console.log(results); // Logs all results once they're done
};

forEach and await

Avoid using await in forEach because forEach does not respect await, resulting in asynchronous operations starting without waiting.

items.forEach(async (item) => {
  await fetchData(item); // This doesn't wait
});

A for...of loop with await is appropriate for sequential asynchronous operations, but for concurrent operations, consider using Promise.all.


Pitfalls to Avoid
  • Using await in forEach or map without careful consideration.
  • Forgetting to handle errors in parallel processing.
  • Overloading the system with too many concurrent operations.

Accounting.js Branding Cascading StyleSheet Cheat Sheet Competitors Connect Content Type CSS Currency Date Formats Dates Flows Hillbilly Tabs HTML5 Javascript JavsScript JSON Format View NodeJs Numeral.js O365 Office 365 OneDrive Out Of The Box Overflow Permissions PnP PowerAutomate Power Automate PowerShell Pwermissions ReactJs Rest Endpoint Send an HTTP Request to SharePoint SharePoint SharePoint Modern SharePoint Online SharePoint Tabs ShellScript SPFX SPO Styling Sync Teams App Transform JS TypeScript

Leave a Comment

Your email address will not be published. Required fields are marked *