What is the method to retrieve data within a resolved Promise in JavaScript?

Currently, I am delving into the world of promises for the very first time. My goal is to retrieve data (in the form of an array) from two distinct endpoints. Consequently, I have drafted the following code. Upon inspecting my console, I notice that [Promise, Promise] both appear in a resolved state. Interestingly, I can witness the desired response within the data property; however, I remain unsure about how to retrieve this crucial data array. Can anyone provide guidance on accessing the data array from these promises? Thank you.

Console Output Regarding Promises

0: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "Object"
  data: {room 18: {...}, room 19: {...}, room20: {...}} // target data content

1: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "Object"
  data: {room 18: {...},  room 19: {...}, room20: {...}} // target data content
const urls = ['/room/*/userconfig', '/room/*/observation/latest']; 
        let requests = urls.map(url => axios.get(url)); 

        Promise.all([requests])
            .then(res => res.map(response =>  console.log(response) // create 1 array and match roomId data))

Answer №1

Ensure that the requests array is not nested within another array when using Promise.all

let requests = urls.map(url => axios.get(url)); 

Promise.all(requests)
  .then(res => res.map(response => console.log(response));

Answer №2

Make sure your data is received as a single array within the then function:

var promises = [
  new Promise((resolve, reject) => { setTimeout(() => resolve("Hello"), 1000);}),
  new Promise((resolve, reject) => { setTimeout(() => resolve("world !"), 1500);})
];

Promise
  .all(promises)
  .then(results => {
    let mergedResults = results[0] + " " + results[1];
    console.log(mergedResults);
    document.body.innerHTML = mergedResults;
  });

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

Using a Fake Timer to test the setTimeout function for a class method is not possible

One way to test setTimeout with a normal function is by using the following code: function doAsync() { setTimeout(doAsync, 1000) } jest.useFakeTimers() test("setTimeout with function", async () => { doAsync() jest.advanceTimersByTime(2 ...

I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Her ...

Combining GET and POST requests in ExpressJS on a single route

As I work on setting up a questionnaire in Express JS with EJS as the renderer, I have already created individual pages for each question. These pages are accessible through static links using the app.get('/question/:number?', routes.questions) f ...

Is it possible to keep adding the keys of an array to themselves until reaching a specified limit

Given an array var ary = [5,10,28,50,56,280], I am exploring the idea of generating all possible combinations or subsets of this array until a certain threshold is reached. The objective is to store this limit in a variable and collect all the elements be ...

Limiting the display of JSON data on a webpage using jQuery

I have a code snippet on my website that displays JSON data on an HTML page. The issue is that there is a large amount of data in the JSON file. How can I limit the number of movies (data) being displayed to just 5? function actors(actors) { return ` ...

Encountered an error with the post request in expess.js: TypeError - Unable to access the property 'fullName' as it is undefined

Hey everyone, I'm new to Express and having trouble posting data from Postman. The error message I'm getting is "TypeError: Cannot read property 'fullName' of undefined". Does anyone have any suggestions on how to fix this? Thank you! ...

Click on the submenu to expand it, then simply select the desired option to navigate

I have created a toggle menu that displays a list of child elements when clicked, and hides them if clicked again. However, when a child element is clicked, I want it to navigate to the corresponding page. I am having trouble getting this functionality to ...

WebVTT captions on a Chromecast receiver as the default option

Trying to set up closed captions for chromecast using the default Chrome sender app but it's not working. The code is similar to the sample provided in the docs, seen here. I've shared a snippet that might be too sandboxed, view it on a normal ht ...

The system is unable to show real-time data at the moment due to an error message being returned: {"error": "'QuerySet' object has no attribute 'body'"}

I am looking to integrate real-time data display in a Django application using Ajax. My goal is to allow users to see what they are typing as they type it, and I am achieving this by utilizing Django's JsonResponse with the following method: def get_ ...

Tips for adding and verifying arrays within forms using Angular2

Within my JavaScript model, this.profile, there exists a property named emails. This property is an array composed of objects with the properties {email, isDefault, status}. Following this, I proceed to define it as shown below: this.profileForm = this ...

Generate a form using code that has the trigger turned off by default

Summary: Looking for a solution to avoid the automatic disabling of a programmatically created trigger in a form. function autoTrigger(e) { var result = {}; var responses = e.response.getItemResponses(); for (var i = 0; i < responses.length; i++) ...

Dynamically obtaining the screen width in JSP using a variable

Could someone provide assistance on how to resize an image using an img src="blah.jpg?width=x" so that my page can be displayed at various sizes? I just need x (width) as a JSP variable. Update 2021: It's been 9 years since this question wa ...

JavaScript GridView

Is there a way to determine if an ASP.NET GridView contains at least one row by using JavaScript? ...

code, scripting - modal pop-up

My script currently has a popup window using window.open, but most browsers block this type of popups. I now want to change it to another popup that includes a php script, similar to what I've seen on other sites. It seems like they are using ajax. Ca ...

Creating a one-of-a-kind entry by adding a number in JavaScript

I am looking for a way to automatically add an incrementing number to filenames in my database if the filename already exists. For example, if I try to add a file with the name DOC and it is already present as DOC-1, then the new filename should be DOC-2. ...

Error: Trying to access the 'commit' property of an undefined variable in Angular

I am currently working on a project that involves Angular and Spring Boot integration. The project retrieves parameters from the Spring Boot back-end through a DTO, and I display this information on the front-end screen. However, upon showing the dialog co ...

There is an issue with loading Google Maps on ASP.NET

My C# Web Application (asp.net web-forms) has a peculiar issue within the Default.aspx page that is part of a Master Page. The google map embedded within the content flickers once but never fully loads. Surprisingly, when I transfer the exact code from Con ...

Implementing Bootstrap modal functionality in PHP

I'm attempting to trigger a hidden modal from an HTML file using PHP as part of a verification process. One modal is displayed when a button is clicked, while the other is meant to be called by PHP. Below is my PHP code: $File = include("index2.html ...

Is it possible to adjust a CSS value once a JS value hits a specific threshold?

Currently, I am developing a web game where the website displays different emotions, including anger. I have successfully implemented the anger level internal coding and I am now focusing on adding a color-changing feature when the anger level reaches a sp ...

The if-else condition is creating issues with the functionality of the buttons

Update #1 - Enhanced query, fresh functional link. Live site: The challenge at hand revolves around an if-else statement related to the form buttons on the right-hand column of the webpage. Scroll past the header and navigation to witness the issue in ...