Promise.all does not wait for the inner Promise.all to complete before continuing

let dataObj = [
  {
    Id: 1,
    name: 'Alice',
    Address:[{
      city: 'Paris',
      country: 'France'
    }]
  },
  {
    Id: 2,
    name: 'Bob',
    Address: [{
      city: 'NYC',
      country: 'USA'
    },
    {
      city: 'Beijing',
      country: 'China'
    }]
  }
];

async function processData() {
await Promise.all(dataObj.map(async details => {
      console.log('details', JSON.stringify(details));
      await Promise.all(details.Address.map(async (locations, idx) => {
        console.log('ParentLocations IsUpdatedCapability',);
        let result = await innerFunction();
        console.log('promise resolved: ' + result)
        console.log('proceeding to next step');
      }));
      console.log('ModifiedDetails', JSON.stringify(dataObj));
    }));
}
 async function innerFunction() {
  return new Promise((resolve, reject) => {
    let x = 0;
    setTimeout(() => {
      for (let j = 0; i < 10; i++) {
        x++;
      }
      console.log('iterating completed');
      resolve(x);
    }, 2000);
  });
 }

processData();

My current output is as follows:

  1. details
  2. details
  3. iterating completed
  4. promise resolved
  5. proceeding to next step
  6. ModifiedDetails
  7. Iterating completed
  8. proceeding to the next step
  9. ModifiedDetails

Desired output should look like this:

  1. details
  2. iterating completed
  3. Promise resolved: 10
  4. next step
  5. ModifiedDetails
  6. details
  7. iterating completed
  8. promise resolved: 10
  9. proceeding to next step
  10. ModifiedDetails

Answer №1

When utilizing .map(async (e) => {...}), all the functions are initiated simultaneously. Using

await Promise.all(arr.map(async (e) => {...}))
ensures that all functions finish, but they still run in parallel.

If you want to execute them sequentially, you have a couple of options:

for (let info of obj) {
      console.log('info', JSON.stringify(info));
      for (let index = 0 ; index < info.Address.length; index++) {
        let items = info.Address[index];
        console.log('ParentItems IsParentLossCapability',);
        let pr = await firstFunction();
        console.log('promise resolved: ' + pr)
        console.log('next step');
      }
      console.log('UpdatedInfo', JSON.stringify(obj));
}

or utilize an async reduce function:

await obj.reduce(async (memo, info) => {
      await memo;
      console.log('info', JSON.stringify(info));
      await info.Address.reduce(async (memo2, items, index) => {
        await memo2;
        console.log('ParentItems IsParentLossCapability',);
        let pr = await firstFunction();
        console.log('promise resolved: ' + pr)
        console.log('next step');
      }), Promise.resolve());
      console.log('UpdatedInfo', JSON.stringify(obj));
    }, Promise.resolve());

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

Laravel 4 - Error: Uncaught TypeError - Unable to access property 'post' as it is undefined

Here is the script I am using: <script> function selectModSetProd(prodId,setId,objControl){ function ifOK(r){ objControl.style.background="'"+r.color+"'"; } function ifError(e){ alert( ...

Leveraging the power of context to fetch data from a store in a React component within the Next

I'm having trouble with the title in my React project, and I'm new to React and Nextjs. When trying to fetch data from my dummy chat messages, I encountered this error: × TypeError: undefined is not iterable (cannot read property Symbol(Sy ...

Sort arrays in Javascript by their respective lengths

Is there a way to arrange these arrays in descending order of the number of items they contain? I believe the logic is correct, but I might be missing some essential methods. The current output is empty. //Declare Variables var TN = ['Chattanooga&apo ...

Save information in a nested object within local storage by utilizing a dynamic key

Storing the below object in localStorage to simulate server-side login/logout functionalities. Current user logic is implemented to identify the logged-in user. let defaultUsers = [ { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Retrieving information from a function within a Node module

Struggling to get data returned from a function in my Node module. I've researched and read but can't seem to crack it. Using the request plugin to fetch JSON data from an API and aiming to pass that data back for use. Below is my module code: ...

Retrieve the string saved in a ViewBag when the ajax call is successful

I am new to ASP.NET MVC and have been struggling to find a solution to this problem. Despite searching on various platforms, including Stack Overflow, I have not been able to resolve it. Here are some links to solutions that did not work for me: Possible ...

Changing a particular field value within an array of objects in Angular 4

I have a scenario where I created a class called security: class security { public id:number; public name:string; } Next, I initialized an array of security objects: let s:security[]=[{id:1,name:'Alex'},{id:2,name:'John'},{id:3,nam ...

Menu only appears with a double click on the label button

Currently, I'm facing an issue where I have to click the label "button" (hamburger menu) twice in order to show the menu for the second time. My belief is that there might be a conflict between CSS and jQuery causing this behavior. The desired funct ...

Prevent parent element from triggering double click when double clicking on children element with CSS or jQuery

Check out my project demo here Whenever I double click on a child element, it also triggers the parent element at the same time. I want to prevent this behavior so that only the child element is affected by the double click event. Can anyone provide assis ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

Tips for managing erroneous data in csv files using Node.js

I am currently working on an application that parses csv files using the csv module. It is functioning well, but I am facing a problem where if there is a bad row in the csv file, the entire process fails. Is there a way to skip bad rows and continue stre ...

Limit the radio button to being clickable

Ugh, I'm really struggling with this. I want to create a quiz where only the radio button is clickable, not the text itself. Can anyone help me figure out how to do this? I have two codes below that I don't quite understand. I'll include th ...

Save an array of messages by making separate API calls for each one

I have a function that makes an API call to retrieve a list of message IDs. Here is the code: function getMessageList(auth) { api.users.messages.list({ auth: auth, userId: 'me', }, function(err, response) { if (er ...

Default cross-origin behavior of the Fetch API

According to the Fetch Specifications, the default Fetch mode is 'no-cors'. The specifications state that a request's mode can be "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless otherwise specified, it defaults to "no ...

JavaScript data manipulation: Determining percentage change within a nested JSON structure

Provided is a JSON file structured like this... data =[ { key: "london", values: [ {day: "2020-01-01", city: "london", value: 10}, {day: "2020-01-02", city: "london", value: 20}, {day: " ...

NodeJS Error: Attempting to access 'json' property from an undefined source

I'm in the process of setting up a CronJob to make an API call and save the response into the database: const CronJob = require("cron").CronJob; const btc_price_ticker = require("../../controllers/BtcExchange/Ticker"); const currency = require("../.. ...

Odd behavior observed while running npm scripts in the npm terminal

Included in my package.json file are the following dependencies: "devDependencies": { "chromedriver": "^2.37.0", "geckodriver": "^1.11.0", "nightwatch": "^0.9.20", "selenium-server": "^3.11.0" }, "scripts": { "e2e": "nightwatch -c test ...

Display a thumbnail image using a v-for loop

Looking for help with implementing a photo preview in my code using BootstrapVue. The Vue devtools show that the form-file contains the image, but my 'watch' isn't functioning properly. Any assistance would be greatly appreciated! Here is ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...

What is the strategy to load a div exclusively when triggered by a click event, instead of loading it

Can anyone assist me with a problem I am facing on my scripting page? I am currently working on a website that showcases properties. I would like to know how to prevent a specific div from loading when the page initially loads, and instead have its content ...