从递归for循环接收结果时遇到问题。我正在进行递归,以获取“ myArray”的“汽车”和“船”,但它没有等待。因此,当我点击下载json时,json中没有“ cars”和“ ships”。在控制台中,我看到点击下载后递归完成。
任何想法都如何等待从递归for循环接收结果然后才开始下载?
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);
}
在控制台中,如果将console.log放在每个方法中,您将看到类似的内容:
1
2
3
(15)2 //换句话说,再次调用循环方法15次
答案 0 :(得分:0)
我认为array.prototype.find()
是同步的,因此它不支持promise,它被认为是同步运行的功能。我建议您看一下StackOverflow上的这篇帖子,发现的问题与您发布的问题类似。也许您觉得这很有用。