Executing a for loop concurrently by utilizing async/await promises

In my current code, I am using a for loop structured like this:

async myFunc() {
    for (l of myList) {
        let res1 = await func1(l)
        if (res1 == undefined) continue

        let res2 = await func2(res1)
        if (res2 == undefined) continue

        if (res2 > 5) {
            ... and so on
        }
    }
}

The issue here is that func1 and func2 are network calls that return promises, and I don't want them to slow down my for loop while waiting for their completion. I'm open to processing myList[0] and myList[1] concurrently, and I don't have a preference for the order in which the list items are handled.

How can I modify my code to achieve this parallel processing?

Answer №1

To simplify the process, create a function that deals with handling one value at a time sequentially:

async function handleOneValue(value) {
    let result1 = await function1(value);
    if (result1 == undefined) {
        return /*insert appropriate value*/;
    }

    let result2 = await function2(result1);
    if (result2 == undefined) {
        return /*insert appropriate value*/;
    }

    if (result2 > 5) {
        // continue with more operations
    }
}

Next, utilize Promise.all along with map to initiate all these functions concurrently, obtaining the results in an array (if needed):

function executeFunctions() {
    return Promise.all(myList.map(handleOneValue)); // Assuming that 'handleOneValue' is designed to be called using 'map'
    // return Promise.all(myList.map(value => handleOneValue(value))); // Use this if the assumption shouldn't be made
}

If 'myList' is not always an array, transform it into an array using Array.from before employing map:

function executeFunctions() {
    return Promise.all(Array.from(myList).map(handleOneValue));
}

(Alternatively, use a 'for-of' loop to push values into an array.)

If you don't want a failure in handling one entry to halt the processing of others, consider using Promise.allSettled instead of Promise.all. (Note that all functions will still be initiated, and the only difference is in whether you receive successful results when one fails.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate highcharts data into your Laravel project using the power of AJAX

Encountering an issue with loading data for a Highcharts chart. The response from my controller provides the following data: [['Doctorado', 91.86],['Maestría', 6.98],['Licenciatura', 1.16]] Although the AJAX call is succes ...

When setting an attribute on load, Javascript may not properly apply the change to the attribute

I designed a webpage where images have a fade-in effect using a CSS class. Initially, 4 images load with the desired effect. However, I encounter an issue when trying to apply the same effect to a new image that appears upon clicking a button. Below is th ...

Updating from webpack v1 to v2 using webpack-cli results in a tsx error during migration

Encountering an error during the build process after migration, I'm unsure if it's related to the recognition of tsx files or something within them that is causing issues: Failed to compile. Error in ./src/index_app.tsx Module parse fail ...

The backbone module is experiencing formatting issues

I'm new to learning backbone.js. I've created the example below, but unfortunately, it's not functioning properly. Can someone please help me understand why? The goal is to simply display the name within my div element. (function($) { ...

Utilize AJAX in JavaScript file

I am encountering an issue with the following code: function inicioConsultar(){ $(function(){ $('#serviciosU').change(function(){ if ($('#serviciosU').val()!= "-1") { $.ajax({ url: "@Url. ...

Designing a visual showcase with interactive tab links for image selection

I have been working on developing an Angular component that simulates a tab gallery functionality, inspired by this example. Below is my HTML structure: <div class="gallery-container"> <div class="display-container"> ...

How can you transfer data from a jQuery function to a designated div element?

I'm struggling to transfer data from a function to a specific div, but I can't seem to make it work. I'm in the process of creating a gallery viewer and all I want is to pass the counter variable, which I use to display images, and the total ...

reversing an array does not have an effect

Whenever I attempt to reverse the order of my array using the reverse() function, the changes do not reflect in the view until I make a change to the file and save it. Items.js: import { useState } from "react"; const Items = (props) => { ...

What is the best way to extract menu and submenu information from an array?

I'm in the process of building a webpage with the help of smart admin and I'm facing an issue with displaying left menu data properly. The data is being retrieved from an array and I need to arrange the menus and submenus based on the parent ID o ...

Is it possible to determine the duration of a JQuery AJAX call's execution?

Is it possible to measure the duration of a $.getJSON method call using timing code in jQuery/JavaScript? Additionally, is there a method to determine the size of the response Content-Length, measured in kilobytes or megabytes? ...

Exploring TypeScript Module Importation and WebPack Integration

Struggling with WebPack's injection of imported dependencies for a TypeScript project. The first challenge is getting TypeScript to recognize the imported module. In the header.ts file, there is a declaration of a module nested under vi.input, export ...

Issue: Module '../utils/composeObjs' not found after global installation of generator-stencil

Currently, I am in the process of developing a generator for stenciljs which can be found at https://github.com/AkashGutha/generator-stencil Within this project, there is a handy utility function located at the root directory. This function resides in one ...

Configuration of an MVC-based web application

As a newcomer to web application development, I am currently working on building a web application using the Model-View-Controller pattern. My setup includes a MySQL database for the Model, JSP pages for the Views, and a DAO for the Controller. I am looki ...

Error thrown due to missing property in type '{}' when using TypeScript arrow function parameter

As outlined in the documentation for interfaces in TypeScript, An interface declaration serves as an alternative way to define an object type. I'm puzzled by the error I encounter in the following code snippet. My attempt is to restrict the object ...

The logout confirmation message functionality in Laravel 8 is malfunctioning

In my Laravel project, I am attempting to implement a logout confirmation message that will pop up when a user clicks on the logout button. Here is the code I have added to my navbar.blade.php: <a class="dropdown-item" id="logout" hr ...

Filtering options in a dropdown box with jQuery

I have implemented a feature where the content of one select box is filtered based on the option selected in another select box. Below is the code snippet that achieves this functionality: // Filter content based on the selected option in a region select ...

Organize my JavaScript code by implementing a function

I have repetitive javascript code that I would like to refactor into a function. Is there a way to streamline this process and make the code more efficient? The two functions I want to consolidate are: bright() $(VARIABLE).find('.info').fadeTo ...

Creating diverse content for various tabs using JavaScript

I have developed a code that uses a for loop to generate tabs based on user input. var tabs = ""; var y = 1; for (var x = 0; x < tabNum; x++) { tabs += "<li class = 'tabbers'>" + "<a href='#tab'>Tab</a>" + "& ...

Is subtyping causing issues in TypeScript's inheritance model?

I am currently utilizing TypeScript for my coding projects, and I have observed that it can allow the production of non-type-safe code. Despite implementing all the "strict" options available to me, the behavior I am experiencing goes against the principle ...

Manage interfaces and structures

I am looking to implement user roles in my application. Here is a snippet of the code I would like to use: export interface User{ name: string roles: Roles[] } interface Roles{ ADMIN: new Permissions(1,1,1,1,1), MOD: new Permissions(1,0,1,1,0,0), [. ...