What is the best way to combine two responses and then convert them into a promise?

When making two calls, the firstCallData prints data fine. However, when I use + to merge the responses, it returns me the following Response. What is a better approach to achieve this task?

main.ts

let data = await this.processResponse(__data.Details[0]);
    
console.log("firstCallData", data);
    
data += await this.orderResponse(__data.Details[1]);
    
console.log("DATA", data);
return Promise.resolve(data);

Response:

[object Object][object Object]

Answer №1

One effective method to combine object properties in JavaScript is by using Object.assign(). This function copies all enumerable own properties from one or more source objects into a target object and returns the updated target object.

When using Object.assign(), it merges values of multiple objects while prioritizing the source object's properties over the target object's. For more information, refer to this MDN link.

Here is an example illustrating how Object.assign() can be utilized:

let data1 = await this.processResponse(__data.Details[0]); //Assuming the promise resolves to {foo: 4, bar: 49}

console.log("firstCallData" , data1);

let data2 = await this.orderResponse(__data.Details[1]); //Assuming this promise resolves to {baz: 69, bar: 42}

data = Object.assign(data2, data1);

console.log("DATA", data);
return Promise.resolve(data);

By executing the above code snippet, the resultant merged object would be:

{foo: 4, bar: 49, baz: 69}

Note that when there are overlapping properties between the source and target objects, Object.assign() will prioritize the source object's properties.

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

Why am I seeing numbers in the output when I log the data from the res.write(data) function in Node.js?

While working with Node.js on my Raspberry Pi, I encountered an issue where reading a local file 'test.html' resulted in hex output instead of the expected HTML format. Can someone explain why this might be happening? Additionally, I am aware tha ...

Merge the variables extracted from an array of objects

I need to extract specific data from an array of objects and perform a calculation. For example, the provided data is as follows: const item = [{ "act": "Q", "line": 1, &quo ...

Retrieving a targeted JSON element and adding it to a fresh object

Hello everyone, I have an object that resembles the following structure: [ { "app": 1, "scalable": true, "zoomable": true, "cropBoxResizable": true }, { "app" ...

Adjust the color of the font within a div element when hovering over it

I've been attempting to modify the text color and add an underline when a user hovers over it. Despite trying various methods, I haven't been successful. I scoured the internet for a solution but couldn't find one that met my specific requi ...

The heap limit has been reached in Github Actions, causing an allocation failure

Encountering a heap out of memory error in Github Action during the last "run: npm run build". FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory Error: Process completed with exit code 1. Showcasing the workflow file: name: ...

What is the process for transferring a function to reducers in Redux Toolkit?

In one of my files called Main.tsx, I have a function that sends a request and retrieves data: async function fetchProducts(productsPage = 1, id?: number) { const itemsPerPage = 5 let url: string if (id) { url = `https://reqres.in/api/ ...

What sets usePreloadedQuery apart from useQueryLoader?

I've been exploring graphQL and the react-relay library. These are the key points I've covered: Rendering Queries: where usePreloadedQuery is introduced. Fetching Queries for Render: where useQueryLoader is introduced. To keep it simple, I&apo ...

The function with which you are trying to use 'new' does not have a call or construct signature

How can I prevent the error from appearing in my console.log? An error message - 'Cannot use 'new' with an expression whose type lacks a call or construct signature.' - keeps popping up. var audioContext = new window.AudioContext() ...

Having difficulty invoking a JavaScript function at a global level

Currently, I am working on a nodejs application that involves mongoDB integration. In my code, I have created a function to extract specific data from MongoDB and save it in a variable called "docs". Despite multiple attempts to declare the function global ...

How to smoothly transition a div from one location to another using animations in an Ionic3-Angular4 application

I'm attempting to incorporate some animation into my Ionic 3 mobile app. Specifically, I want to shift a div from one location to another. In the code snippet provided below, I am looking to move the div with the "upper" class after the timeline-item ...

KendokendoNumericTextBox Unable to assign a value

After upgrading to the latest version of Kendo 2020, everything seems to be working smoothly except for the kendonumerictextbox control. I encountered an error when attempting to set a value to the kendonumerictextbox. $('#Taxes').data("kendoNu ...

The Bootstrap modal-backdrop dilemma requiring JavaScript intervention

I am encountering some problems with the Bootstrap modal. When I try to open a modal, everything looks good, but when I close it, the screen turns completely black. Upon closer inspection, I found that every time I click on the X to close the modal, there ...

Customize button text in Vue using data variable conditions

There are 3 desks in a table with role IDs 2, 4, and 6. In this scenario, two tables are involved. The goal is to dynamically display a specific role name on a button based on the current user's role ID. The desired displays are: If the current use ...

Passing a variable from a service to a controller in AngularJS

I recently developed a basic app that includes user authentication based on the guidelines found in this useful resource. The core components of my app are a userAccountService, which manages communication with the server, and a login controller that over ...

``There seems to be an issue with setting the input value attribute using jQuery's .html

I've been trying to update the value attribute in the input element within my HTML code, but so far, I haven't had any luck with it. HTML: <div class='photo-info'> Photo Name : <span class='photo-name'><?p ...

What is the reason behind having a selectedOptions property rather than just a selectedOption?

Why does the selectedOptions property of select return an HTMLCollection instead of just one HTMLOptionElement? As far as I understand (correct me if I'm wrong), a select element can only have one selected option, so why do I always need to access it ...

Table sorting feature with checkboxes has disappeared from view

This segment of code includes HTML for a table along with JavaScript functionality. When a checkbox is clicked, another table will be displayed: <form class="filter"> <input type="checkbox" id="checkboxID" class="unchecked"> EG <input type= ...

Is there a way to use jQuery to eliminate divs that contain multiple identical data values?

Is there a way to accomplish this? <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="14-March-2016" ...

Issue: subscribe function is not definedDescription: There seems to be an

I'm currently trying to retrieve a value from an array based on a specific element, and then finding the exact matching element. Unfortunately, I've encountered an error with this.getProduct(name1: string) function even though I have already impo ...

variance in efficiency when retrieving a DOM element

While this may not make much of a difference for smaller, simpler DOM elements, the performance impact could be significant when dealing with larger, more complex ones. Is there a noticeable performance gap between storing an element in a variable and cons ...