简体   繁体   中英

Wait for For loop to finish - Angular

I have this code that formats the parameters and submits to api.

                for (let a = 0; a < perfCriteria.length; a++) {
                    const element = perfCriteria[a];
                    let newObject = Object.assign({}, paramObject)
                    newObject.performanceCriteria = element.performanceCriteriaId
                    for (let b = 0; b < element.performanceIndicators.length; b++) {
                        const element2 = element.performanceIndicators[b];
                        let newObject2 = Object.assign({}, newObject)
                        newObject2.performanceIndicator = element2.performanceIndicatorId
                        newObject2.numberTarget = element2.divisionTarget ? element2.divisionTarget : ""
                        newObject2.targetDetails = element2.targetDetails
                        for (let c = 0; c < element2.targetDetails.length; c++) {
                            const element = element2.targetDetails[c];
                            element2.targetDetails[c].individualAccountable = element.individualAccountable.map(function(row){
                                return row._id
                            })
                        }

                        divTargetArray.push(newObject2)
                    }
                }

                this.DivisionTarget.create(divTargetArray).subscribe(result =>{
                    console.log('result', result)
                    if(result.success){
                        this.appComponent.showLoadingIndicator = false;
                        this.router.navigate(['/index/app/performanceManagement/divisionTargets']);
                        this.toastService.openSnackBar(result.message, "success");
                    }else{
                        this.appComponent.showLoadingIndicator = false;
                        this.toastService.openSnackBar(result.message, "danger");
                    }
                }, error => {
                    this.appComponent.showLoadingIndicator = false;
                    this.toastService.openSnackBar(error, "danger");
                });

But sometimes, it will not wait for the For loop to finish. Is there a way that I can wait for the For loop to finish before proceeding to submit it to API?

I can't see any asynchronous operations in your code so I think it's executed line by line. It seems like there is no possibility that subscription happens before loop has ended. Maybe issue is somewhere else?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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