Wait for the completion of a Promise inside a for-loop in Javascript before returning the response

After completing a Promise within a for-loop, I am attempting to formulate a response.

Although I have reviewed these questions, my scenario remains unaddressed.

The methodGetOrders and methodGetLines are components of an external library that must be utilized. Both imply network calls, resulting in some anticipated delay. Currently, the function simply returns '0' as it does not await the resolution of the inner promise. While acknowledging the inability to directly 'wait' for promise completion, how can I attain the accurate value of counter in the response?

doWorkMainFunction() {
  methodGetOrders()
    .then(orderList =>  {
       var counter=0;
       for (var i=0; i< orderList.length; i++) {
         methodGetLines()
           .then (lineData => {
              if (someCondition) { counter++; }
            } // end of inner THEN
       } // end FOR loop
       return counter; // This always returns '0'
   } // end of outer THEN
}

Answer №1

Generate an array comprising all promises within the loop and utilize Promise.all() to yield the counter value once all promises have been resolved

methodGetOrders()
  .then(orderList => {
    var counter = 0;

    var promises = orderList.map(order => {
      return methodGetLines()
        .then(lineData => {
          if (someCondition) {
            counter++;
          }
        }) // end of inner THEN
    }) // end promise map
    return Promise.all(promises).then(_ => counter);
  }) // end of outer THEN
})

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

React Alert: "Unable to modify while in the middle of a state transition"

Currently, I am working on developing an application that involves utilizing a toastr component. However, I am encountering an error when attempting to dispatch a redux action within this particular component. The error message displayed in the console is ...

The content of the text does not align. Alert in React 16

Currently, I am working on developing a ReactJs application with server-side rendering. Here are my entry points for both the client and server: client.jsx const store = createStore(window.__INITIAL_STATE__); hydrate( <Provider store={store}> ...

Passing state from a parent component to a child component and then down to subsequent child components through props in React.js

Currently, all the data is static information. I am using a parent state which is an array containing 4 objects: function App(){ const [searchResults,setSearchResults] = useState([ { name: 'name1', artist: 'artist ...

Can two different versions of ReactJS run simultaneously on a single page?

Hey everyone, I'm curious if it's possible to have two different versions of ReactJS running on the same page, similar to how jQuery has jQuery.noConflict(). After doing some research, I came across some interesting findings: Two Reacts Won’t B ...

Tips for ensuring proper function of bullets in glidejs

I am currently working on implementing glidejs as a slider for a website, but I am facing issues with the bullet navigation. The example on glidejs' website shows the bullets at the bottom of the slider (you can view it here: ). On my site, the bullet ...

Is the object returned by the useParams hook maintained across renders?

The book that is displayed is based on the URL parameter obtained from the useParams hook. The selected book remains constant across renders unless there is a change in the value returned by the useParams hook. I am curious to find out if the object retur ...

Engage with React JS arrays of objects

I have a specific object structure that looks like the following: [ { "periodname": "Test", "periodtime": "" }, { "periodname": "", "periodtime&quo ...

ways of exporting and using arrays in Node.js

Constantly receiving the "undefined" error in main.js: var dbAccess = require('../dao/dbAccess'); dbaInstance = new dbAccess(); var wordPool = dbaInstance.getWordPool(); console.log (wordPool); The contents of "dbAccess.js" are as follows: var ...

Express identifies the user, however, the username is displayed exclusively on one specific page. This situation may indicate a potential cookie problem

I am in the process of developing an express app integrated with MongoDB. The issue I am facing involves a pug template for the navigation bar where I aim to display the user's name at the top upon logging in. Strangely, it only works on the page that ...

X-Ray Rendering in Three.js and Webgl

Looking to create an x-ray effect in three.js / webgl. Something like this: UPDATE I am seeking help on how to achieve a real-time render with the x-ray effect, instead of just a static image. This can be accomplished using shaders that modify density i ...

Using PHP to set cookies after making an AJAX request

After reviewing numerous posts on this topic, I am still unable to set any cookies with my code. The initial ajax call in my code looks like this: $("#loginForm").submit(function(event) { event.preventDefault(); var uid = document.getElementById( ...

Enhance the current MultiSelect object by incorporating JQuery MultiSelect

Is there a way to detect changes on a JQuery MultiSelect in order to trigger an update elsewhere? The typical javascript onchange method does not seem to work because the select itself does not change. However, I came across a method called "beforeclose" t ...

Execute JavaScript unit tests directly within the Visual Studio environment

In search of a method to run JavaScript unit tests within the Visual Studio IDE, I currently utilize TestDriven.net for my C# units tests. It's convenient to quickly view the test results in the output pane and I am seeking a similar experience for Ja ...

I am unable to load any HTML files in my VueJS iframe, except for the index.html located in the public

Within the template of my vue component, I am utilizing the following code: <iframe width="1000vw" height="600vh" src="../../public/myHtmlFile.html"></iframe> Unfortunately, the file specified in the src attribut ...

React Material-UI select component malfunctions when I enclose the menu item within a Tooltip wrapper

Here is a snippet of my code: return( <FormControl sx={{ m: 1, minWidth: 80 }}> <InputLabel id="demo-simple-select-autowidth-label">Age</InputLabel> <Select labelId="demo-simple-select-autowidt ...

What is the solution to the error "Maximum update depth exceeded. Calls to setState inside componentWillUpdate or componentDidUpdate" in React?

Everything was running smoothly until this unexpected issue appeared. I attempted to change the condition to componentDidMount, but unfortunately, that didn't resolve the problem. The error is occurring in this particular function. componentDidUpd ...

What is the best way to retrieve JSON data using JavaScript within a loop?

I'm struggling to retrieve data from a JSON object. Here's the JSON structure I'm working with: var data = [ {"mes":{ "January":{ "Inversion":"1000","Fans":"1020"} ...

AngularJS issue: Form submission does not trigger the controller function

I am currently learning AngularJS and I am experimenting with the sample code below to send my form data to the server. <!doctype html> <html lang=''> <head> <meta charset="utf-8"> <script src="../js/angular.min.v1 ...

Exploring the Use of 7BitEncodedInt in JavaScript

Currently, I am trying to read a binary file using JavaScript. It appears that this file may have been written in C#, which handles strings differently from how it's done in the source mentioned at https://learn.microsoft.com/en-us/dotnet/api/system. ...

Importing images with relative paths from a JSON file does not work as expected in Next.js

JSON file data portion: { "categories": [ { "id": 1, "category_slug": "food_supplements", "title": "Food Supplements", "image": "/../../public/images/foodSupplements.png", } ] } Component data portion that displays the ...