Dealing with numerous promises nested within a single promise

I'm in the process of developing a service method that fetches data from an API and returns it as a promise. The challenge here is that I need to ensure that the parent object, along with all its child objects, are fully retrieved before resolving the outer promise. The code snippet below demonstrates what I have so far, but I am struggling to make the promise wait for all child objects to be resolved before completion.

private obtainRegistrationData(url: string): Promise<MyType> {    
  return new Promise((resolve) => {
     this.dataService.fetchMyType(url)
       .then((myType: MyType) => {                    
          _.forEach(myType.childReferences, (childUrl) => {
            let childPromise = this.dataService.getChild(childUrl).then((child) => {
                myType.children.push(child);
            };
        };                  
        return x;
    });
});

Answer №1

Replace the usage of _.forEach with .map(), and make sure to return the nested promise within the callback.
By doing this, you will have an array of promises.

After obtaining the array of promises, you can utilize Promise.all() to create a single promise that waits for all of them to resolve.

Lastly, ensure to return this final promise from your chain of promises.

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

Arrange, Explore (Refine), Segment HTML Chart

Is there a way to efficiently sort, paginate, and search (based on a specific column) data in an HTML table? I've explored several JQuery plugins such as DataTable, TableSorter, Picnet Table Filter, but none seem to offer all three functionalities (se ...

Tips for modifying the content displayed on a v-list in Vue.js dynamically

I am looking to create a dynamic list that displays data based on the selected key. The list will contain multiple items with different keys, and I want the flexibility to choose which data to display without hardcoding the actual key value. <template&g ...

Troubles arise when using $resource without initializing it with the new operator

Trying to utilize the Angular promise API in my application has left me feeling a bit puzzled. I set up a factory as shown in the code snippet below: factory('transport', function ($resource) { var baseUrl = "http://aw353/WebServer/odata/Pay ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...

Remove any current query parameters from the Angular UI Router when navigating to the same route

I am currently using angular ui router to navigate between different pages and I have a route that includes multiple query parameters. The issue I am encountering is that when I switch routes for the same page with new query parameters, the existing parame ...

discovering the absence of any letters within an array

Looking for a way to find multiple missing letters in an array? Check out this code snippet: function missingLetters(str) { var nums = str.split('').map(function(letter){ return letter.charCodeAt(); }) var result = []; for(va ...

Meteor fails to fetch data from Mongo database

Struggling to retrieve an array from Mongo within Meteor, despite successful push operations. Any assistance would be greatly valued. Below is the HTML code: <ul class="schedule"> {{#each employee.schedule}} <li class="schedule_item" ...

Uploading an image to the server using JQuery library and FormData

I have reviewed numerous solutions, but I am unable to identify the issue in my code. HTML: <div id='image-uploader-view'> <input type='text' id='rename' name='rename'/> <input id='fileu ...

What is the best way to locate the index of a td element that contains the text "Up" using jQuery, and then utilize that index to choose the corresponding

I have a table that has the following structure: <table> <tr><td>a</td><td>b</td><td>up</td><td>d</td></tr> <tr><td>0</td><td>1</td><td>99</td>< ...

Leveraging interfaces with the logical OR operator

Imagine a scenario where we have a slider component with an Input that can accept either Products or Teasers. public productsWithTeasers: (Product | Teaser)[]; When attempting to iterate through this array, an error is thrown in VS Code. <div *ngFor= ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...

Access Denied while attempting to use Firebase

Exploring the integration of Firebase with my ionic application for the first time has presented a challenge. Despite configuring the project and linking the necessary javascript files, I encounter the frustrating 'Error: Permission Denied' when ...

Encountering repeated requests (duplicating calls) for each API request while using AngularJS with a JWT authentication token

I'm experiencing a problem with AngularJS(2/4) while attempting to make API calls. The issue arises when each API request contains a JWT Auth Token header, resulting in duplicate API calls. The first request returns no response (despite receiving a 20 ...

Implementing dynamic component rendering and iterating through a list in React JS based on state changes

Trying out React JS for the first time and encountering a couple of issues. 1) Attempting to display a table from a different class upon clicking the show button. However, even when the state is true for showing the table, it doesn't appear. 2) In t ...

Managing an Angular timer: Starting and resetting it via the controller

Is there a way to start a timer when the user clicks on the recordLogs method and reset the timer when the user clicks on the stopLogs method? According to the angular-timer documentation, we should be able to use the timer-stop and timer-clear methods to ...

What is the method for incorporating locales into getStaticPaths in Next.js?

I am currently utilizing Strapi as a CMS and dealing with querying for slugs. My goal is to generate static pages using getStaticPaths and getStaticProps in Next.js. Since I'm working with multiple locales, I have to iterate through the locales to re ...

Guide to refining a JSON array using a pre-established list

I'm in need of assistance figuring out how to accomplish the following task: Below is the code snippet I am working with: public class Data { public string FirstName; public string LastName; public int Age; } var data = new Data { //this objec ...

Is it feasible to determine the specific memory address of an Object in a program?

Is it possible in JavaScript to determine the memory location and memory usage of an object? Any assistance on this matter would be greatly appreciated. ...

Running a JavaScript file from a C# application

I am currently using a .js file to create an array of strings, and I find that Javascript is the most suitable language for this task. However, I am now looking to access this array in my C# application. Since Javascript is unable to access the filesystem ...

Angular implementation of Owl Carousel Events

Incorporating owl-carousel version 2.0.7 into my angular application, I have opted to create custom Prev & Next buttons instead of using the default nav text option. Can you provide guidance on how to implement functionality for navigating to the next and ...