0

I call an api inside a forEach, then i push the result of the api in an array, the problem is that the array is empty outside of the forEach.

        this.apiConvention.findConventionsRCSendedUsingPOST(this.exerciceFramework.specialities.map((speciality: any) => speciality.code)).subscribe((data: any[]) => {
            if (data) {
                let array: any[] = [];
                data.forEach(convention => {
                    this.apiConvention.findAgreementFileByConventionUsingGET(convention.externalId, this.exerciceFramework.externalId).subscribe((agreementFile: any) => {
                        if (agreementFile) {
                            array.push(this.initData(convention, agreementFile));
                        }
                    })
                })
                console.log(array); // empty
            }
        })

I tries also with async and await, but the same problem remains

        let data: any[] = await this.apiConvention.findConventionsRCSendedUsingPOST(this.exerciceFramework.specialities.map((speciality: any) => speciality.code)).toPromise();
        if (data) {
            let array: any[] = [];
            data.forEach(async convention => {
                let agreementFile: any = await this.apiConvention.findAgreementFileByConventionUsingGET(convention.externalId, this.exerciceFramework.externalId).toPromise();
                if (agreementFile) {
                    array.push(this.initData(convention, agreementFile));
                }
            })
            console.log(array); // empty
        }
Aymen Kanzari
  • 1,765
  • 7
  • 41
  • 73
  • This is asynchronous, so outside subscribe it will (most likely) be an empty array. – AT82 Dec 10 '21 at 09:47
  • @AT82 I tries also with async and await, but the same problem remains. – Aymen Kanzari Dec 10 '21 at 09:54
  • Maybe you want to look into `forkJoin` instead of foreach, you can run all in paralell and handle everything inside a single subscribe. – AT82 Dec 10 '21 at 09:56
  • I would recommend that instead: https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin – AT82 Dec 10 '21 at 09:57

0 Answers0