angular - 为未来执行创建一系列承诺
问题描述
我创建了一个数组来存储应在单次调用 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()
则在删除发生之前调用。
解决方案
这条线断了:
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() ) );
推荐阅读
- azure - 使用 .json 脚本自动化 CI/CD
- python - 关闭多处理记录器处理程序
- mongodb - $rename - 重命名嵌入文档中的字段
- python-3.x - how to read gml file with label in jupyter notebook?
- python - 导入bloomberg Api 时出错,如何解决?
- algorithm - 如何提高掺杂矩阵构建算法的速度
- c# - PdfBox 图像提取:该库从文档中为每一页提取所有图像
- node.js - Laravel-Echo + Passport 认证 + Node JS 客户端
- php - 无法在服务器上上传文件 - 错误是警告:POST Content-Length of 42669632 bytes exceeded
- cuda - WMMA 默认内核