我在这里尝试使函数等待数组迭代的结束。如果我理解正确,则此功能应等待所有诺言得到解决,然后继续。为什么这不是那样?
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
答案 0 :(得分:2)
您的代码应更改为:-
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');
}), catchError(() => console.log(error))).toPromise();
}
}));
console.log('DONE');
if (updated) {
this.toastrService.success('Settings succsessfully updated.');
}
}