等待Promise.All都没有在Anuglar中等待
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了等待Promise.All都没有在Anuglar中等待相关的知识,希望对你有一定的参考价值。
我正在这里尝试使函数等待数组迭代的结束。如果我理解正确,则此功能应等待所有诺言得到解决,然后继续。为什么这不是那样?
async onUpdateSettings() {
let updated = false;
await Promise.all(Object.keys(this.settingsForm.controls).map(async (key) => {
if (this.settingsForm.controls[key].dirty) {
const toUpdateSetting = this.peopleSettings.find(ps => ps.settingKey.includes(key));
toUpdateSetting.settingValue = this.settingsForm.get(key).value;
this.peopleSettingsService.updateSetting(toUpdateSetting).subscribe(() => {
updated = true;
console.log('UPDATE');
}, (error) => console.log(error));
}
}));
console.log('DONE');
if (updated) {
this.toastrService.success('Settings succsessfully updated.');
}
}
// results always in:
// DONE
// UPDATE UPDATE UPDATE
答案
您的代码应更改为:-
async onUpdateSettings() {
let updated = false;
await Promise.all(Object.keys(this.settingsForm.controls).map(async (key) => {
if (this.settingsForm.controls[key].dirty) {
const toUpdateSetting = this.peopleSettings.find(ps => ps.settingKey.includes(key));
toUpdateSetting.settingValue = this.settingsForm.get(key).value;
return this.peopleSettingsService.updateSetting(toUpdateSetting).pipe(map(() => {
updated = true;
console.log('UPDATE');
}, (error) => console.log(error))).toPromise();
}
}));
console.log('DONE');
if (updated) {
this.toastrService.success('Settings succsessfully updated.');
}
}
以上是关于等待Promise.All都没有在Anuglar中等待的主要内容,如果未能解决你的问题,请参考以下文章