简体   繁体   English

等待循环首先完成 - Typescript (Angular)

[英]Wait loop to finish first - Typescript (Angular)

So I have this code here triggered using click on HTML page:所以我在这里使用点击 HTML 页面触发了这个代码:

public salaryConfirmation() {
    const matDialogConfig: MatDialogConfig = _.cloneDeep(GajiIdSettings.DIALOG_CONFIG);
    this.warningNameList = [];

    for(let i=0; i < this.kelolaDataPenggajianInfoDataKaryawanList.length; i++) {
      const positionClassId = this.selectedKaryawanAllData[i].position.positionClass.id;
      const beginYearMonth = this.inputForm.get('bulanBerlaku').value;
      const gajiPokok = this.kelolaDataPenggajianInfoDataKaryawanList[i].gaji;

      this.structureAndSalaryScaleValidationService.getSalaryRange(positionClassId, beginYearMonth, gajiPokok)
        .pipe(takeUntil(this.ngUnsubscribe))
        .subscribe(
          async (result) => {
            this.uiBlockService.hideUiBlock();
            if(result.status == 'warning') {
              if(result.warnings[0].code == 'trxMutasiKaryawan.confirmation.alert') {
                await this.warningNameList.push(this.kelolaDataPenggajianInfoDataKaryawanList[i]);
              }
            }
          },
          (error) => {
            this.uiBlockService.hideUiBlock();
            this.contentAlertService.error(error.errors);
          },
          () => { this.uiBlockService.hideUiBlock(); }
        )
    }

    matDialogConfig.data = this.warningNameList;
    console.log("this.warningNameList.length :", this.warningNameList.length);

    if (this.warningNameList.length > 0) {
      this.save();
    } else {
      this.inputMassalGajiWarningComponentDialogRef = this.dialog.open(InputMassalGajiWarningComponent, matDialogConfig);
      this.inputMassalGajiWarningComponentDialogRef.afterClosed().subscribe(
        (confirm: boolean) => {
          if (confirm) {
            this.save();
          }
        }
      );
    }
  }

The problem is, I tried to catch the length of this.warningNameList variable.问题是,我试图捕捉 this.warningNameList 变量的长度。 But it always shows "0" on the result.但它总是在结果上显示“0”。

I know the problem is because this should be work in asynchronously .我知道问题是因为这应该是异步工作的。 But I don't know how to apply it in typescript.但我不知道如何在 typescript 中应用它。 Been search this case but I always failed to apply.一直在搜索这个案例,但我总是申请失败。 Anyone can help me out?任何人都可以帮助我吗?

I already put await inside the loop, but seems it's not working because of wrong placement.我已经将 await 放入循环中,但似乎由于放置错误而无法正常工作。

Some reference that I found out there is this => JavaScript async and await in loops我发现的一些参考是这个=> JavaScript async and await in loops

Thanks in advance提前致谢

Putting await inside loop is not gonna help you.将 await 放入循环不会对您有所帮助。 as it is running in a different context already.因为它已经在不同的上下文中运行。

What you need to do is probably chain this 2 operations one after another after using promise instead of observable here.您需要做的可能是在使用 promise 而不是此处的 observable 之后依次链接这两个操作。

you can probably do something like this,你可能可以做这样的事情,

public async salaryConfirmation() {
    const matDialogConfig: MatDialogConfig = _.cloneDeep(GajiIdSettings.DIALOG_CONFIG);
    this.warningNameList = [];

    for(let i=0; i < this.kelolaDataPenggajianInfoDataKaryawanList.length; i++) {
      const positionClassId = this.selectedKaryawanAllData[i].position.positionClass.id;
      const beginYearMonth = this.inputForm.get('bulanBerlaku').value;
      const gajiPokok = this.kelolaDataPenggajianInfoDataKaryawanList[i].gaji;

      let result = await this.structureAndSalaryScaleValidationService.getSalaryRange(positionClassId, beginYearMonth, gajiPokok)
        .pipe(takeUntil(this.ngUnsubscribe)).toPromise();

      // Transform following data
      // .subscribe(
      //    async (result) => {
      //      this.uiBlockService.hideUiBlock();
      //      if(result.status == 'warning') {
      //        if(result.warnings[0].code == 'trxMutasiKaryawan.confirmation.alert') {
      //          await this.warningNameList.push(this.kelolaDataPenggajianInfoDataKaryawanList[i]);
      //        }
      //      }
      //    },
      //    (error) => {
      //      this.uiBlockService.hideUiBlock();
      //      this.contentAlertService.error(error.errors);
      //    },
      //    () => { this.uiBlockService.hideUiBlock(); }
      //  )
    }

    matDialogConfig.data = this.warningNameList;
    console.log("this.warningNameList.length :", this.warningNameList.length);

    if (this.warningNameList.length > 0) {
      this.save();
    } else {
      this.inputMassalGajiWarningComponentDialogRef = this.dialog.open(InputMassalGajiWarningComponent, matDialogConfig);
      this.inputMassalGajiWarningComponentDialogRef.afterClosed().subscribe(
        (confirm: boolean) => {
          if (confirm) {
            this.save();
          }
        }
      );
    }
  }

Just like above code convert observables to promise, don't subscribe them.就像上面的代码将 observables 转换为 promise,不要订阅它们。 This way you can use async await syntax with obervables as well, although find out how to handle errors this way.这样,您也可以将 async await 语法与 obervables 一起使用,尽管了解如何以这种方式处理错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM