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

The Vue.js class bound to the object remains static even after the object is updated

When I have a number of buttons, generated using the v-for directive, with each button having an initial class based on a string from an object. There is an event that changes this string when a button is clicked. However, the class does not get updated a ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...

Combining a name using JavaScript even if certain parts are not available

How can I efficiently combine name elements without any extra white space in Vue.js? let FirstName = "John" let MI = "G" let LastName = "Jones" let Suffix = "Jr." I want to create let fullName = "John G Jones Jr." However, in cases like this: let First ...

Displaying live data from a spreadsheet directly on a sidebar

My goal is to extract data from another sheet in the same spreadsheet and present it as a dropdown selection in the sidebar. The code.gs file contains a function called getVisualData() that successfully retrieves the desired list: function getVisualData() ...

Printing the result of an SQL query in Node.js without using braces

As a beginner in node.js with only a basic understanding of javascript, I apologize if I make any mistakes. I attempted to display the results retrieved by an SQL query in node.js using: <p>Users are " + util.inspect(results) + ".</p>" an ...

Is there a way to divide my time during work hours using Javascript?

This is just a simple example. 9.00 - 18.00 I am looking to modify the schedule as follows: 9.00 - 10.00 10.00 - 11.00 11.00 - 12.00 12.00 - 13.00 13.00 - 14.00 14.00 - 15.00 15.00 - 16.00 16.00 - 17.00 17.00 - 18.00 The current code implementation see ...

Building a collapsible toggle feature with an SVG icon using HTML and CSS

I am trying to swap a FontAwesome Icon with a Google Materials SVG Icon when a collapsible table button toggle is pressed (changing from a down arrow to an up arrow). I have been struggling to get the Google Material Icons code to work. How can I resolve t ...

Utilizing Async.each fails to trigger the ultimate callback function

Here's the scenario: I expect the function finalCallBack to be triggered after we finish looping through all elements. var rows = [ { name: 'first'}, { name: 'second'} ]; var execForEachRow = function(row, callback){ var ...

React application not displaying element properly?

I am facing an issue with my react modal that displays a sign-in and sign-up form. The problem arises when I try to access the button on the form using its id, which is modal-sign-in-submit-button. document.getElementById('modal-sign-in-submit-button ...

Combining disparate arrays with serialized name/value pairs

Is there a way to merge an unassociated array with serialized name/value pairs without manually iterating over them? //First, I select certain values from mytable var data = $('#mytable input:checked'); console.log(data); //Object[input attribu ...

How to make an Ajax "POST" request to the server using jQuery or AngularJS without sending any parameter data

"Execute a 'POST' request to the server by using the code provided below However, the parameter data is not being sent to the server. I have attempted both the jQuery Way and var request = $.ajax({ url: baseUrl, type:'post', da ...

A guide on sorting JSON data with Javascript/jquery

I have a set of JSON data: {"X1":"3","X2":"34","Y1":"23","Y2":"23","Z1":"234","Z2":"43",...} My goal is to rearrange and group this data as follows: var newDataJson1 = { "X":{"X1":"3","X2":34}, "Y":{"Y1":"23","Y2":"23"}, ... } ALSO, I want to stru ...

Traverse a computed attribute in Vue.js

I am working with a component that contains a simple array as its data: data() { return { roles: [ { id: '1' , name: 'admin'}, { id: '2' , name: 'user'}, { id: &a ...

jQuery: Set default option selected or reset value

I'm attempting to change the value of the nearest select option dynamically. $(document).ready(function () { $('.limitation_points').hide(); $('.field .limitSelected').each(function () { $(this).change(function ( ...

"Although Vuex data is present, an error is being logged in the JavaScript console

I'm utilizing Vuex to retrieve data from a URL and I need to use this data in computed properties in Vue.js. What could be causing the issue? <script> import {mapGetters, mapActions} from "vuex"; computed: { ...mapGetters(["ON ...

Router Express, parsing the body, and submitting a POST request

I have been experimenting with express.Router to organize my routes and testing post requests using Postman. I noticed that when I make a post request to /test without using router body-parser, everything works fine and I can view the body content. However ...

What is preventing the factory from gaining access to the controller?

I have set up a notification factory and passed it inside the controller. However, when I try to assign the factory to the scope within the controller, I am encountering an error. alertsManager MyApp.factory('alertsManager', function() { ...

Modify the variable for each VU in K6 (refresh token)

When I start my K6 test, I utilize my setup() function to obtain a token that will be used by every VU. I want each VU to have the same token, rather than generating individual tokens for each one. Although this works fine initially, the challenge arises ...

Utilize the Power of React.js and Express.js to Send Emails

After building a web app using React.js in ES6, I found myself wanting to add a "Contact Us" page that allows users to send an email. However, as a newcomer to React, I discovered that React itself cannot directly send emails. Following tutorials with node ...