等待Angular 8中的递归For循环



从递归for循环接收结果时出现问题。我正在为"myArray"做一个递归,以获得"cars"one_answers"ships",但它并没有等待。所以当我点击下载json时,json没有"cars"one_answers"ships"。在控制台中,我看到递归在我点击下载后完成。

有什么想法吗?如何等待递归for循环的结果,然后开始下载?

myservices.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);

}

在控制台中,如果在每个方法中放入console.log,您会看到类似的内容:

1

2

3

(15( 2//换句话说,再次调用循环方法15次

我认为array.prototype.find()是同步的,因此它不支持promise,它是一个被认为是同步运行的函数。我建议你看看StackOverflow的这篇文章,其中有一个问题和你发布的问题一样。也许你觉得这很有用。

在Array.find((中使用异步函数

最新更新