Приписать много обещаний? - PullRequest
0 голосов
/ 23 июня 2019

Я новичок в angular и столкнулся с проблемой, когда мне нужно вызвать несколько обещаний и получить все их результаты, прежде чем продолжить процесс.

// Let's assume this array is already populated
objects: any[];

// DB calls
insertObject(obj1: any): Promise<any> {
  return this.insertDB('/create.json', obj1);
}

updateObject(obj: any): Promise<any> {
  return this.updateDB('/update.json', obj);
}

// UI invokes this:
save(): void {
  this.insertObject(objects[0])
  .then((result) => {
    console.log(result.data[0].id);
  })
  .catch((reason) => {
    console.debug("[insert] error", reason);
  });

  this.insertObject(objects[1])
  .then((result) => {
    console.log(result.data[0].id);
  })
  .catch((reason) => {
    console.debug("[insert] error", reason);
  });

  this.updateObject(objects[1])
  .then((result) => {
    console.log(result.data[0].status);
  })
  .catch((reason) => {
    console.debug("[update] error", reason);
  });

  //I need to catch these 3 results in order to perform the next action.

}

Есть идеи, как этого добиться?

1 Ответ

0 голосов
/ 24 июня 2019

Используя синтаксис Promise.all (итерируемый), вы можете выполнить массив Promises.Этот метод разрешается, когда все обещания разрешены, и не выполняется, если любое из этих обещаний не выполняется.

Это может помочь вам

let firstPromise = Promise.resolve(10);
let secondPromise = Promise.resolve(5);
let thirdPromise = Promise.resolve(20);

Promise
 .all([firstPromise, secondPromise, thirdPromise])
 .then(values => {
 console.log(values);
 });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...