Having problems in receiving result from a recursive for loop. I am doing a recursion to get "cars" and "ships" for "myArray" but it is not awaiting. So when I hit to download the json, the json comes without "cars" and "ships". In the console i see that the recursion finishes after I hit the download.
Any ideias how can await to receive result from recursive for loop and just then start the download?
myservice.ts ----------------------------------------------------------------------
public async callData(): Promise<myType> {
return new Promise<myType>(async (resolve, reject)=>{
this.toDownload.myArray = await this.loop(this.toDownload.myArray);
resolve(this.toDownload);
});
}
private async loop(myArray:[]): Promise<myArray[]> {
return new Promise<myArray[]>(async (resolve, reject) => {
for (let i: number = 0; i < myArray.length; i++) {
myArray[i].id = .....
myArray[i].cars = this.carsArray.find(....)
myArray[i].ships = this.shipArray.find(....)
if (myArray[i].subMyArray.length !== 0) {
await this.loop(myArray[i].subMyArray);
}
}
resolve(myArray);
});
}
mycomponent.ts-----------------------------------------------------------------
public async donwload(){
this.myArray = await myservice.callData();
// this.myArray comes without .cars and .ships
const jsonStr: string = JSON.stringify(this.myArray);
}
In the console you would see something like this if put console.log in each method:
1
2
3
(15) 2 // in other words calling again the loop method 15 times