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.

Automation Cascading StyleSheet Cheat Sheet Collaboration Competitors Content Type CSS Currency Design Flows HTML5 Intl Issues Javascript JavsScript JSON Format View Luxon Microsoft Teams ModernScriptEditor Myths NodeJs O365 Office 365 OneDrive Overflow PnP PowerAutomate Power Automate PowerShell Rest Endpoint scss Send an HTTP Request to SharePoint SharePoint SharePoint Architecture SharePoint Designs SharePoint Modern SharePoint Online SPFX SPO Styling Sync Teams Teams App Termstore Workflows

Leave a Comment

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