等待Promise.All不在Angular中等待

时间:2020-05-28 09:33:12

标签: javascript angular promise async-await

我在这里尝试使函数等待数组迭代的结束。如果我理解正确,则此功能应等待所有诺言得到解决,然后继续。为什么这不是那样?

     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

1 个答案:

答案 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.');
        }
      }