Asynchronous Iteration

Asynchronous iteration allows looping over asynchronous data streams using for-await-of, we can use await keyword in for/of loop.

Syntax:

for await (variable of asynchronousIterable) {
  // Code to be executed for each iteration
};

Example: In this example, we use async/await to iterate through myArray, calling doSomethingAsync() for each item. It waits for asynchronous tasks to complete before moving to the next iteration

Javascript




const myArray = [1, 2, 3, 4, 5];
  
// A function that returns a promise
// that resolves after a random delay
async function doSomethingAsync(item) {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(item);
            resolve();
        }, Math.random() * 1000);
    });
}
  
async function main() {
    // Iterate over the array using a for-of loop
    for (const item of myArray) {
        // Wait for the promise returned 
        //by doSomethingAsync to resolve
        await doSomethingAsync(item);
    }
}
  
// Call main to start the program.
main();


Output:

JS 2018 – ECMAScript 2018

JavaScript 2018 (ES9) or ECMAScript 2018 is a modified version of ES8, in which ES9 introduced new features like asynchronous iteration, rest/spread properties, and enhancements to regular expressions, further improving asynchronous programming, object manipulation, and string handling capabilities.

JavaScript 2018 (ES9) or ECMAScript 2018 new features are:

  • Asynchronous Iteration
  • Promise Finally
  • Object Rest Properties
  • New RegExp Features
  • SharedArrayBuffer

We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Method 1: Asynchronous Iteration

Asynchronous iteration allows looping over asynchronous data streams using for-await-of, we can use await keyword in for/of loop....

Method 2: Promise Finally

...

Method 3: Object Rest Properties

Promise.finally() executes a callback when a promise settles, either resolved or rejected, allowing cleanup operations regardless of the promise outcome....

Method 4: New RegExp Features

...

Method 5: SharedArrayBuffer

Object Rest Properties allow creating new objects with selected properties, simplifying object destructuring and recombination in JavaScript....