Я создал массив для хранения списка обещаний, которые должны запускаться после одного вызова Promise.all, однако сразу после помещения этого нового 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) => {
});
UPDATE
Следуя советам @ 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()
будет вызван до того, как произойдет удаление.