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

Yearly Grouping with MongoDB's Aggregate Framework

I've been experimenting with the aggregate function to group date fields by year: db.identities.aggregate([ { $group : { _id : { year : {$year : "$birth_date"}}, total : {$sum : 1} } } ]) However, I encountered a c ...

How can I streamline a kendo UI MVC project by eliminating unnecessary components?

After switching my MVC 5 project to utilize Kendo UI, I've noticed a significant increase in the number of files being used. Since there is no need for supporting other cultures at the moment, can I confidently delete the files within the messages an ...

Is it possible to restrict contenteditable elements to only accept numbers?

Is there a way to restrict contenteditable elements such that only numerical values can be entered? I attempted to use the following code snippet: onkeypress='return event.charCode >= 48 && event.charCode <= 57' However, despite a ...

What steps do I need to take to ensure that this Regex pattern only recognizes percentages?

I am attempting to create a specific scenario where I can restrict my string to three digits, followed by a dot and two optional digits after the dot. For example: 100.00 1 10.56 31.5 I've developed a regex pattern that allows me to filter out any ...

Tips for incorporating a custom CSS design into a jQueryUI tooltip

I am struggling to apply my custom CSS class on top of the jQueryUI tooltip. Although the tooltip is displaying correctly, my styles are not being applied. Here is the code I'm using: $(document).ready(function () { $("#roles").tooltip({ content: ...

I'm experiencing issues with my code involving HTML, CSS, and jQuery

Recently, I started learning about jQuery and came across a tutorial on creating a sticky nav bar. However, something went wrong during the implementation and now I don't know how to fix it! In my Script file, I have written code that should run on l ...

When attempting to use JSON.parse, it returns an undefined value

When using PHP to create JSON data and retrieving it through AJAX, why does JSON.parse return an "undefined" object? PHP CODE $emparray = array(); while($row =mysqli_fetch_assoc($result)) { $emparray[] = $row; } echo json_encode($emparray); AJ ...

Struggles encountered while configuring React

I'm in need of assistance with setting up React, even though I have both Node and npm installed. When I enter the following command: npx create-react-app new-test-react --use-npm I encounter the following error message: npm ERR! code ENOTFOUND npm E ...

Adjusting package.json settings for an npm module

An npm package that I am using has an incorrect file path specified in its package.json. The current configuration is: "main": "./htmldiff.js", However, for it to function correctly, it should be: "main": "./src/html ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

The optimal method for selecting a button from a group of buttons on a calculator using pure JavaScript

I have developed an HTML/CSS code inspired by the Mac/Apple calculator design. It features buttons organized in 5 rows using flexbox. You can view my code on this codepen: <div class="wrapper"> <div class="calheader"> ...

The provider of $modalInstance is currently unknown, leading to an error in the MainController

I'm currently facing an issue with my app's modals when trying to call them using $modalInstance. Despite following the advice from other similar questions I found, such as avoiding the use of ng-controller, my modal still isn't functioning ...

Integrate JQuery-Ui into an Angular 7 application using an external .js file

I'm currently working on an Angular 7 project and facing some challenges while trying to integrate the JQuery-Ui plugin. I have successfully installed both JQuery and the plugin, and added them to the scripts array in my angular.json file. Even though ...

EJS forEach method not displaying output

Trying to work with this .ejs file that's supposed to loop through an object and retrieve data from an API. However, after fetching the data, it appears that nothing is being displayed on the screen. I've checked the API results in the console l ...

How can Vue.js transfer form data values (using v-model) from a Parent component to a Child component?

I am working on a multistep form using vue.js. The parent form collects two inputs and once these are validated, it moves to the next step which involves a child component. I want to pass the values from the parent component to the child component's f ...

What is the best way to remove a border piece with CSS?

Currently, I'm attempting to achieve a matrix effect purely through HTML and CSS. One method I have come across involves applying a solid border and then removing certain parts at the top and bottom. Does anyone know if it's possible to create th ...

Achieve uninterrupted deployment of node.js applications by utilizing naught for zero downtime implementation

Recently, I began utilizing naught for deploying my node.js applications (https://github.com/andrewrk/naught). In my Ubuntu Server, I have a directory that contains my node.js (express) app. To deploy it, I used the command "naught start app.js" from tha ...

What is the best way to sequentially slide down multiple elements with a time delay in between each one?

I have multiple div elements with the same class. I have selected them all and I am iterating through each one to slide down every element. My goal is to first slide down the initial element, then introduce a delay before moving on to the next slide. Here ...

Display the header on every single page using puppeteer

            Whenever I enable displayHeaderFooter, the header does not display. It only works if I add margin to @page in my CSS, but this causes the page height to increase by the margin value and content to overflow beyond the page boundaries. Is ...

Instructions on creating a JSON patch in Django REST Framework

I have a PATCH button in my ModelViewSet https://i.sstatic.net/qoQLu.png class CompanyViewSet(viewsets.ModelViewSet): serializer_class = s.CompanySerializer queryset = m.Company.objects.all() def patch(self, request, id, format=None): ...