首页 > 解决方案 > 为未来执行创建一系列承诺

问题描述

我创建了一个数组来存储应在单次调用 Promise.all 后运行的 Promise 列表,但是在将这个新的 Promise 推入数组后它会立即执行。我该如何解决?

let promises: any[] = [];

this.tasklistItems.forEach(element => {
  if (element.checked) {
     promises.push(new Promise(() => this.tasklistItemsService.delete(this.tasklist, element.id))); // It gets executed right after this line
  }
});

Promise.all(promises) // But I need to start executing here
  .then((res) => { // So I can get all responses at the same place, together
    this.notification.success('Success!', 'Rows removed.');
  },
  (err) => {
  });

更新

按照@Evert 的建议,现在我有以下代码:

  const deferred = [];
  this.tasklistItems.forEach(element => {
    if (element.checked) {
      deferred.push(() => this.tasklistItemsService.delete(this.tasklist, element.id).subscribe());
    }
  });

  Promise.all(deferred.map(func => func()))
    .then(
      () => {
        this.notification.success('Sucess!', 'Rows removed.');
        this.refreshGrid();
      },
      err => {
        console.log(err);
        this.notification.error('Error!', 'Could not remove the selected rows.');
      }
    );

这是我使用的服务HttpClient

  delete(tasklistId: number, id: number): Observable<boolean> {
    return this.http.delete(`${this.baseUrl}/${tasklistId}/items/${id}`)
      .pipe(catchError(this.handleError));
  }

如果我不添加subscribe()delete(...)调用中,它不会被执行,如果我添加它,refreshGrid()则在删除发生之前调用。

标签: angulartypescriptpromise

解决方案


这条线断了:

new Promise(() => this.tasklistItemsService.delete(this.tasklist, element.id)

除此之外,promise 通常会立即执行。它们不是一种将执行推迟到以后的机制。值得庆幸的是,javascript 有一些非常简单的东西:一个普通的旧函数。

const deferred = [];
this.tasklistItems.forEach(element => {
  if (element.checked) {
    deferred.push(() => this.tasklistItemsService.delete(this.tasklist, element.id)));
  }
}

// Iterates over all stored functions, calls them all and returns the result as an array of promises.
Promise.all( deferred.map( func => func() ) );

推荐阅读