Mapping promises with arrays of objects containing arrays

I am currently working with the following complex data structure:

[
  {
    "id": 1,
    "houses": [
      {
        "id": 1,
        "name": "house 1"
      },
      {
        "id": 2,
        "name": "house 2"
      }
    ]
  },
  {
    "id": 2,
    "houses": [
      {
        "id": 3,
        "name": "house 3"
      }
    ]
  }
]

In my project, I need to perform an asynchronous operation for each house in each user. To achieve this, I have a function that returns a promise and has the following signature:

sendWelcomeEmail(user, house)

While I am familiar with using Bluebird's Promise.map when dealing with arrays of promises, my situation involves arrays of objects with nested arrays. What would be the correct approach to utilize Promise.map in order to execute sendWelcomeEmail for every user and house?

Answer №1

Understanding Promise.all in JavaScript

The Promise.all(iterable) method is a powerful tool that consolidates multiple promises into a single promise, resolving when all promises within the iterable argument have resolved or when there are no promises left to resolve. If any promise rejects, the overall promise will reject with the reason of the first rejection encountered.

const data = [{
    "id": 1,
    "houses": [{
        "id": 1,
        "name": "house 1"
      },
      {
        "id": 2,
        "name": "house 2"
      }
    ]
  },
  {
    "id": 2,
    "houses": [{
      "id": 3,
      "name": "house 3"
    }]
  }
];

const fakeSendWelcomeEmail = (id, house) => Promise.resolve(`${id} / ${house.name}`);

// Transforming the data into a flat array that contains the return value of fakeSendWelcomeEmail.
// Essentially creating an array of Promises.
const welcomeResults = data.reduce((res, user) => {
  return res.concat(user.houses.map((house) => {
    return fakeSendWelcomeEmail(user.id, house)
  }));
}, [])

Promise.all(welcomeResults)
  .then((results) => {
    console.log(results);
  })

If you're interested in delving deeper into how Promises function behind the scenes, I've also developed my own Promise polyfill which may provide valuable insights.

Answer №2

In order to achieve the desired outcome, you should utilize a combination of reduce and map methods.

const promises = mainArray.reduce((acc, cur) => {
  return acc.concat(cur.houses.map(house => sendWelcomeEmail(house)));
}, []);

The variable 'promises' will contain an array that consists of 3 promises based on the example provided.

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

Struggling with a 400 Bad Request Error in Angular with WebAPI Integration

I've been working on creating a database to keep track of comics, and so far I can successfully add new comics and retrieve them using GET requests. However, I've hit a roadblock when trying to update existing comics using PUT requests. Every tim ...

Executing JavaScript code with Node.js while utilizing Selenium

Seeking guidance as a beginner in Javascript, I apologize if my question is too basic. I am attempting to execute a Selenium test written in Javascript. Starting with a simple task of loading Google using chromedriver, I encountered an issue while running ...

What is the best way to set a default date to a specific date obtained from a passed object in props?

I am currently working on populating a form with data retrieved from a database using initial values in Formik. The specific challenge I am facing involves utilizing the Input type = date component from Reactstrap. My goal is to have all fields, including ...

Is there a way to execute a function both upon page load and after a click event?

Greetings! I am completely new to using jQuery in any of my projects and could use some assistance. On one of my web pages, I have implemented code to load menu details from a JSON file. These details include the name, action, and poster for the main menu ...

In PHP/HTML, check if a tab already exists before creating a new one

Currently, I am using PHP to retrieve a list of users from the database and have included a link with them. My goal is to have the linked file open in a new tab, but using target="_blank" causes a new tab to open every time I click on the link. However, I ...

Cookie Strategy for Managing Popups Site-wide

Below is a script that will trigger a popup after 60 seconds of page load. This script also creates a cookie to prevent the popup from appearing more than once. The cookie expires when the user's session ends. However, the popup only appears on the e ...

Please define a unique "redirect_uri" in the FB.ui() function for posting purposes

I'm currently utilizing the "Facebook Javascript Sdk" to publish messages on a user's wall. However, I am facing an issue with dynamic redirect URLs. Even though I am explicitly passing the "redirect_uri" as a link with query string in the FB.ui ...

Obtaining the innerHTML value using JavaScript in an Asp.net Core 5 View

Apologies for any inaccuracies in my English writing. In the Asp.Net Core project view, I am trying to use JavaScript to capture multiple Span tags within innerHTML represented by a loop and display their sum in another tag. However, I am only able to ret ...

Working with Ext JS: Dynamically adjusting panel size when the browser window is resized

I am facing an issue with a side panel in Ext.js. Everything is working fine until I resize the browser, at which point some components of the panel get cut off. https://i.sstatic.net/eaEGI.png Is there a way to make the panel resize automatically when t ...

Constrain the dimensions of images using JavaScript

<input type="file" id="file" accept="image/gif, image/jpeg, image/png"> The structure of this HTML code is as shown. If the input does not contain an image with a 1:1 aspect ratio, I intend to redirect to another page u ...

Implementing relative path 'fetch' in NextJs App Router

When attempting to retrieve data using fetch("/api/status"), the URL is only detected when utilizing the absolute path: fetch("http://localhost:3000/api/status"). This is happening without storing the path in a variable. ...

transferring a delicious cookie to the browser

I have successfully integrated a basic login system using angular, express, and passport.js into an existing project by following the file structure and coding standards provided in angular-passport. Currently, users can sign up and log in without any iss ...

Using async / await in node / express appears to not be waiting for the Promise to resolve before continuing with the code

I have been testing a simple script outside of express, and it works as intended. However, the code below is not meeting my expectations. code async function getTest(type, key) { var body = await tloader.pload(type, key) console.log(body) return bo ...

What is the best way to incorporate jQuery into the head of an HTML document using JavaScript?

I wrote a script to import jQuery into a website, but for some reason, it's not working properly. Here's the code: function loadJQuery() { let jquery = document.createElement('script'); let script = document.createElement('scri ...

Error: The term "OrbitControls" is not recognized in the three

When attempting to import OrbitControls.js, I encounter the following issue: The error message Cannot use import statement outside a module is displayed. To resolve this, I add: <script type="module" src="OrbitControls.js">< ...

Tips for maintaining the position of a camera in three.js while also keeping its rotation fixed on the origin

In three.js, I'm looking to dynamically adjust my camera's position while ensuring that its rotation automatically aligns with the world origin. For instance, if the camera is initially set at: camera.position.set(25,25,25) I aim to have the ...

"Revitalizing DIVs with AngularJS controlled by Rails on the server side

I am using `ng-click' in AngularJS to delete a post from my database. %table.table{"ng-controller" => "PostsCtrl"} %tr %th Title %th .... %th - @posts.each do |post| %tr %td... %td= link_to 'Delete', &apos ...

Executing a function upon clicking a Modal button with Ant Design in a React project

I have implemented a Modal using Antdesign and am trying to trigger a function to log the user out once they confirm the logout action on the Modal pop-up. According to the Antdesign API, I need to utilize the 'onOk' property to call the function ...

Change the height of textarea dynamically using jQuery

I am trying to create a comment box similar to Facebook's, where it resizes as text fills it using Expanding Text Areas Made Elegant This is how my view looks: <div class='expandingArea'> <pre><span></span></ ...

NodeJS assert.AssertionError: How can I eliminate this error?

For my school project, I decided to create a web service using IBM Bluemix. However, I encountered an "assert.AssertionError" when attempting to run the code with "npm start" in the Windows 10 Command Prompt on my localhost. Can someone help me understan ...