Fulfill the promise once all map requests have been completed

Currently, my focus is on developing a bookmark page that retrieves bookmark results with the respective restaurant IDs. Once the response is mapped, I populate an array with objects.

My objective is to ultimately resolve the entire array in order to manipulate the data effectively.

I have implemented a getData function which sends a request to the bookmark API. Upon a successful response, I invoke a function named mapResults as shown below:

mapResults(result: Array<any>, type: string): Promise<any> {
    const promise = new Promise<any>((resolve, reject) => {
        const requests = result.map((res, i) => {
            this.getRestaurantById(res.RestaurantId).then(restaurant => {
                const bookmarks = {
                     createdDate: res.CreatedDate,
                     restaurant: restaurant[0]
                };
                this.savedData[type].push(bookmarks);
            });
        });
        Promise.all(requests).then((completed) => {
            if(completed) {
                console.log(completed)
                resolve(this.savedData[type]);
            }
        })
    });
    return promise;
}

To subscribe, I use the following code snippet:

this.mapResults(result, type).then(data => {
    console.log(data)
});

However, when I view the data output in the console, it shows only the first object instead of the complete data array.

I am puzzled as to why the Promis.all function does not wait for the completion of the mapping process?

Answer №1

There are a few issues within your code snippet:

  • The callback function inside the result.map does not have a return statement
  • Using new Promise is redundant in this context
  • Storing data in a state variable instead of using the promise return value is not recommended
  • The purpose of the completed variable seems unclear

Here is an improved version of the code:

mapResults(result: Array<any>, type: string): Promise<any> {
    // You do not need to wrap "getRestaurantById" in a new Promise since it already returns a promise

    const requests = result.map((res) => {
        // Ensure that you return something from this callback
        return this.getRestaurantById(res.RestaurantId).then(restaurant => {
            return {
                createdDate: res.CreatedDate,
                restaurant: restaurant[0]
            };
        });
    });

    // Using a temporary array like "completed" seems unnecessary and may lead to confusion
    return Promise.all(requests).then((restaurants) => {
        console.log(restaurants)
        // If required, store "restaurants" in "this.savedData[type]"
        return restaurants;
    });
}

Answer №2

Your commitment isn't fulfilled within the scope of the map.

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

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...

Type Error TS2322: Cannot assign type 'Object[]' to type '[Object]'

I'm facing an issue with a code snippet that looks like this: export class TagCloud { tags: [Tag]; locations: [Location]; constructor() { this.tags = new Array<Tag>(); this.locations = new Array<Location>(); ...

What is the most effective method for incorporating CSS using Javascript to target a specific aria-label attribute?

Is there a way to add a CSS property to a specific tag with a particular aria-label on document load? My goal is to change the flex order of a section to 2. I need help using JavaScript to target the aria-label 'block 1' so I can set the order t ...

What exactly does the term "library" refer to in the context of jQuery, a JavaScript

I'm confused about the concept of a library - when it comes to jQuery, can it be described as a large file containing multiple plugins that are pre-made and ready for use? ...

What are some best practices for utilizing `element.offsetParent` in HTML SVG elements?

I'm currently updating some JavaScript code that relies on the .offsetParent property. The recent changes in the application involve the use of SVG elements, which are causing issues with the JavaScript as mySvgElement.offsetParent always returns unde ...

Utilizing AngularJS: Transforming JSONP information into HTML

I'm relatively new to utilizing $http and fetching data from various websites. My main query is, how can I convert JSONP into HTML? Specifically, when using $http to request the Atari Wikipedia page, the content is displayed with and HTML elements. ...

What is the method to remove an authentication code from a JSON file using JavaScript?

Is there a way to delete something from a JSON file? Here is an example: The file I am working with is named test.json Before I delete the authentication code: { "auth": [ { "test": 944037 }, { "tester& ...

Exploring the world of ASP .NET development with the powerful Sonar

We're currently working on an ASP .NET project and are looking for a way to analyze JavaScript files on-the-fly. Unfortunately, SonarLint only offers analysis for C# files. The incremental analysis feature seems to have been phased out, and issues ana ...

Utilize the Bootstrap responsive grid system to ensure that every row is filled with content, creating

I am working with a list of 8 results that I display in a responsive bootstrap grid. However, I want to only show the results that fill up entire rows. For instance, on a medium-sized screen, it appears as 2 rows with 4 results each. On a smaller screen, ...

The Angular service uses httpClient to fetch CSV data and then passes the data to the component in JSON format

I'm currently working on an Angular project where I am building a service to fetch CSV data from an API server and convert it to JSON before passing it to the component. Although the JSON data is successfully logged in the console by the service, the ...

What is the best way to toggle between rendering two components or updating two outlets based on a route in React Router?

There is a React application I am working on that utilizes React-Router. My layout component has the following structure: import React from 'react'; import Header from './components/Header/Header'; import Footer from './components/ ...

Create individual account pages with specific URLs in Next.js

I'm currently working on developing a website that will feature individual user pages showcasing their posts and additional information. I'm facing some difficulty in figuring out how to generate new links to access these user accounts. For insta ...

Tips for maintaining the current route in Vue.js after a page refresh while running the Vue.js project in development mode on a specific port?

In my router.ts file, I have defined two routes: export default new Router({ mode: "history", routes: [ { path: "/", component: require("./components/dashboard/Dashboard.vue")}, { path: "/counter", component: require("./components/ ...

Is there a way to simulate the parameters injected into an fs callback without actually interacting with the filesystem during testing?

I'm currently utilizing Chai, Mocha, and Sinon for my testing framework. At the moment, I have a functioning test, but I find myself having to set up a directory and populate it with files just to make my tests run successfully. This approach doesn&a ...

What is the correct method for completely eliminating a mesh from the three.js scene?

I am looking for a way to fully remove meshes from a three.js scene without causing any memory leaks. I have noticed that reloading the same models multiple times can lead to browser crashes, indicating that memory is not being properly deallocated. ...

You should only call them after the method that returns a promise has completed

submitTCtoDB() { console.log("The selected file list contains: " + this.selectedFileList) this.readFile().then(() => { alert("ReadFile has finished, now submitting TC"); this.submitTC() }); } readFile() { return new Promise((resolve, r ...

Issue with negative z-index in modal window has not been resolved

I'm currently trying to customize the radio button using my own CSS styles, but I've encountered an issue. For some reason, setting the z-index to -1 is not working when the radio button is within a modal. Below is the code snippet that I am wor ...

An instructional guide on seamlessly incorporating a TypeScript variable into an HTML element submission method

A problem arises in my Angular 8/Django 3 app as I attempt to incorporate a server-side variable called client_secret into the stripe.confirmCardPayment() method. The error message that keeps popping up is Property 'client_secret' does not exist ...

How does AngularJS watcher behave when a callback is triggered during a reload or router change?

Can anyone explain why the watch callback is triggered upon browser reload or Angular route change even when the old value and new value are the same? Here's an example: $scope.test = "blah"; $scope.watch("test", function(new, old){ console.log(ne ...

Tips for exporting and reusing third-party types in TypeScript

I am facing a challenge with my package, which relies on a 3rd party package API for most of its functions. How can I export the types from the 3rd party package API in my own package? For instance: React uses @types/react to define its types Let's ...