【发布时间】:2018-08-30 00:43:48
【问题描述】:
我创建了一个数组来存储应在单次调用 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()。
【问题讨论】:
标签: angular typescript promise