How to use for...of and await In Javascript

In this approach, we use a for…of loop with await to handle each element asynchronously and filter the array based on the results.

Example: The below code example is a practical implementation to filter an array using an asynchronous function that returns a promise using for…of and await.

JavaScript
async function filterAsync(array, asyncCallback) {
    const results = [];

    for (const item of array) {
        if (await asyncCallback(item)) {
            results.push(item);
        }
    }

    return results;
}

async function isGreaterThan3(num) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(num > 3);
        }, 100);
    });
}

(async () => {
    let numbers = [1, 2, 3, 4, 5, 6];

    let greaterThanThreeNumbers = await filterAsync(numbers, isGreaterThan3);

    console.log("Numbers Greater Than Three:", greaterThanThreeNumbers);
})();

Output:

Numbers Greater Than Three: [ 4, 5, 6 ]

Time Complexity: O(n)

Auxiliary Space: O(n)



JavaScript Program to Filter an Array with a Function that Returns a Promise

Given an array, our task is to filter its elements using an asynchronous function that returns a promise. This function will determine whether an element should be included in the resulting array.

Example:

Input:   numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Output: Even Numbers: [ 2, 4, 6, 8, 10 ]

Below are the approaches to filter an array using an asynchronous function that returns a promise in JavaScript:

Table of Content

  • Using filter and Promise.all
  • Using for…of and await

Similar Reads

Using filter and Promise.all

In this approach, we use Promise.all to handle the asynchronous operations and filter the array based on the results....

Using for...of and await

In this approach, we use a for…of loop with await to handle each element asynchronously and filter the array based on the results....

Contact Us