JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Async iteration

Async iteration in JavaScript extends the concept of iteration to include asynchronous operations. This feature, introduced in ES2018, allows for iterating over data that arrives asynchronously, such as streams of data fetched over time from a network request. Async iteration is particularly useful when dealing with sequences of data provided on-demand and requires handling each item asynchronously.

Why Use Async Iteration?

Async iteration is essential for scenarios where data elements are not immediately available but arrive incrementally or are fetched in chunks. Traditional synchronous iteration tools like for loops aren’t equipped to handle such cases because they expect all data to be readily available at the time of iteration. Async iterators and asynchronous generators provide a way to process such sequences efficiently and cleanly.

Syntax

Async iteration can be performed using the for-await-of loop, a syntax specifically designed to work with asynchronous iterables—objects that implement the asynchronous iteration protocol.

Javascript
Javascript
. . . .
  • async function iterateAsyncIterable() {...}: Declares an asynchronous function, allowing use of the await keyword.
  • for await (const item of asyncIterable) {...}:
    • for await (...): Iterates over an asynchronous iterable (like an async generator), waiting for each item to resolve.
    • const item: Retrieves and holds each resolved item from the iterable.
    • The loop processes each item sequentially as they become available, ideal for handling data streams or asynchronous sequences efficiently.

Example: Using for-await-of with Async Iterables

Let's look at a practical example where we use for-await-of to iterate over a series of promises that resolve asynchronously.

Javascript
Javascript

. . . .

Explanation:

  • Function fetchDataWithDelay:

    • Defined to mimic the process of fetching data with a delay. It returns a promise that resolves after a specified delay, simulating asynchronous data retrieval.
    • return new Promise(resolve => setTimeout(() => resolve(data), delay));: Returns a promise that resolves with data after delay milliseconds.
  • Asynchronous Generator generateAsyncData:

    • An async generator function that yields promises created by fetchDataWithDelay. Each promise resolves asynchronously, yielding data with a staggered delay.
    • yield fetchDataWithDelay(...): Yields a promise for each piece of data, each resolving after 1 second.
  • Async Function processAsyncData:

    • Begins by logging 'Start processing data'.
    • for await (const data of generateAsyncData()): The for-await-of loop iterates over each promise yielded by the generator function. It waits for each promise to resolve before continuing to the next iteration.
    • Inside the loop, console.log(data): Logs the resolved data from each promise.
    • After the loop, logs 'Finished processing all data', indicating all async operations have been completed.

This example demonstrates how async iteration can be used to handle data that arrives or is processed in stages, which is common in network communications and other asynchronous processing tasks. Async iterators and the for-await-of loop provide a powerful, readable way to manage such scenarios, simplifying the handling of asynchronous data flows.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next