Merging two promises into a single promise in Angular

In my application, I am facing a challenge with implementing a method named loadAll.

What I need to accomplish is to make calls to 2 different HTTP methods in order to load the necessary data.

Both of these methods return promises.

However, when I attempt to combine them into a single promise, I encounter an error.


loadAll() {
    return new Promise((resolve, reject) => {
      resolve(
        this.getAllItem1ToConnect(),
          this.getAllItem2ToConnect();
      );
    }
    );
}

I am aware that this implementation is incorrect. How should I go about solving this issue?

Here is the method for loading Item1:


getAllItem1ToConnect() {
    return this.http.get<Item1[]>(this.path + '/item').toPromise().then((res: Item1[]) => {
      this.items1 = res;
    });
}

Is there a way to merge the functionalities of getAllItem1ToConnect and getAllItem2ToConnect into a single promise?

Answer №1

Utilizing Promise.all is the recommended approach in this scenario. It accepts an array of Promises and consolidates them into a single Promise.

function getResults1() {
  return new Promise( (resolve, reject) => {
    setTimeout(() => resolve('from function 1'), 1000);
  });
}

function getResults2() {
  return new Promise( (resolve, reject) => {
    setTimeout(() => resolve('from function 2'), 1000);
  });
}

Promise.all([getResults1(), getResults2()]).then(result => console.log(result));

In your specific case, the code should look like this:

const combinedPromise = Promise.all([
  this.getAllItem1ToMerge(),
  this.getAllItem2ToMerge()
]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

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

Cross-origin resource sharing (CORS) implemented in an environment combining Electron,

I'm currently working on a desktop application using Electron with Angular for the front end and node.js (express server) for the backend API. The node.js express server is running at http://localhost:3000, while the Angular app wrapped inside electr ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...

TSLint Errors Update: The configuration provided cannot locate implementations for the following rules

After upgrading my tslint to version 4.0.2, I encountered numerous errors like the ones shown below: Could not find implementations for the following rules specified in the configuration: directive-selector-name component-selector-name directi ...

Create a combined string from a structure resembling a tree

In my web application, I have a type that defines the different routes available: interface IRoute { readonly path: string, readonly children?: IRoute[] } I want to create a union type containing all possible paths based on an IRoute object. Let&apos ...

Updating token (JWT) using interceptor in Angular 6

At first, I had a function that checked for the existence of a token and if it wasn't present, redirected the user to the login page. Now, I need to incorporate the logic of token refreshing when it expires using a refresh token. However, I'm enc ...

Conceal the Button when the TextBox does not contain valid input

I'm trying to create a textbox with an email pattern that hides a span (click) if the pattern is invalid. I have the following code snippet in place, but it doesn't seem to work as expected: <input type="text" placeholder="Signup for Mailin ...

Steps for developing a Global service in Angular

I've come across many discussions on global angular services, but none seem to truly embody the concept of "global". I'm curious if it's feasible to develop a service that doesn't require importing everywhere it's used (i.e. truly ...

Steps for adding an array of JSON objects into a single JSON object

I have a JSON array that looks like this: var finalResponse2 = [ {Transaction Amount: {type: "number"}}, {UTR number: {type: "string"}} ] My goal is to convert it into the following format: responses : [ { Transaction Amount: {type: "number"}, UTR numbe ...

What could be the reason my Angular Bearer Token is not showing up in Firefox?

Here is how my function is structured: testFunctionAuth() { const promise = new Promise((resolve, reject) => { this.http.get(AppConfigService.settings.apiServer.rest + 'systems/all', { headers: { 'Authorization': 'B ...

What is the best approach for unit testing canActivate in Angular?

Is there a way to properly test the canActivate function in Angular that returns a function which ultimately provides a boolean value? I attempted to create instances of ActivatedRouteSnapshot and RouterStateSnapshot, and then pass them into the canActiva ...

UI and `setState` out of sync

Creating a website with forum-like features, where different forums are displayed using Next.js and include a pagination button for navigating to the next page. Current implementation involves querying data using getServerSideProps on initial page load, f ...

The error message "NodeJS TypeError: Model is not a constructor" indicates that

I am facing an issue with my Angular5 app making requests to my NodeJS Api. Specifically, when I try to make a put request, it works the first time but throws an error on the second attempt saying that my Model is not a constructor. In my NodeJS backend, I ...

Issue with Formik compatibility in Next JS 14 Application Structure

I attempted to create a basic validation form using Formik. I meticulously followed their tutorial and example, but unfortunately, the form is not functioning correctly. Despite my efforts, I have been unable to identify a solution (Please correct me if I& ...

Unlike other checkbox components, mat-checkbox does not respond to a false condition unless double-clicked

I am dealing with a situation where an entity has a variable that needs to be the opposite of the checkbox state. enitity.enabled = true The checkbox serves as a way to indicate that an item should be deleted. When the form is submitted, the marked item i ...

When running npm start on a Windows system, an error message stating "Node.js version 14.9.0 detected" is displayed

Encountering an error with the npm start command: Node.js version v14.9.0 detected. The Angular CLI requires a minimum Node.js version of either v14.15, or v16.10. Please update your Node.js version or visit https://nodejs.org/ for additional instructions ...

Provide an immutable parameter to a function that will not cause any changes

Looking to develop a function named batchUsers, requiring a parameter of type readonly string in order to create a DataLoader. However, when calling the User.findBy function within my batchUsers function, it's causing issues due to conflicting paramet ...

An issue occurs with Material Dialog getting stuck when it is triggered by clicking on a Leaflet

I'm currently working on a project that involves using a map with ngx-leaflet. When a user clicks on a marker, I want to display a Dialog from Angular Material. Although the Dialog opens successfully, when I click the close button, it reopens and the ...

What steps should I take in order to correctly implement the onChange event and retrieve the event.target.value in my

Incorporating useForm, yupResolver, and Yup for validation caused issues with the previously functioning handleChange function. The value variable doesn't log anything when console.logged, indicating a disconnect with the input field content. Addition ...

Error TS2394: Function implementation does not match overload signature in Typescript

Take a look at this code that seems to be causing headaches for the TypeScript compiler: use(path: PathParams, ...handlers: RequestHandler[]): this use(path: PathParams, ...handlers: RequestHandlerParams[]): this use(...handlers: RequestHandler[]): this u ...

Implementing multer diskStorage with Typescript

I'm currently in the process of converting a node.js server to TypeScript. Here is what my function looks like in Node: const storage = multer.diskStorage({ destination: function (req, file, cb) { const dir = './uploads/'; ...