Angular combine 2 promises to 1 promise

Viewed 564

In my app I am trying to implement a loadAll method.

What needs to be done, is to call 2 http methods to load the data.

These 2 methods return promises.

When I try to combine them to one promise, I get an error.

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

I realize this is wrong, how do I implement this?

getAllItem1ToConnect method:

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

How do I combine getAllItem1ToConnect and getAllItem2ToConnect to 1 promise?

1 Answers

You can use Promise.all. This takes an array of Promises and returns a single Promise.

function func1() {
  return new Promise( (res, rej) => {
    setTimeout(() => res('from func1'), 1000);
  });
}

function func2() {
  return new Promise( (res, rej) => {
    setTimeout(() => res('from func2'), 1000);
  });
}

Promise.all([func1(), func2()]).then( res => console.log(res));

So, in your case, you want:

const promise = Promise.all([
  this.getAllItem1ToConnect(),
  this.getAllItem2ToConnect()
]);

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

Related