【发布时间】:2020-08-01 06:47:51
【问题描述】:
从递归 for 循环接收结果时遇到问题。我正在递归获取“myArray”的“cars”和“ships”,但它没有等待。因此,当我点击下载 json 时,json 没有“汽车”和“船舶”。在控制台中,我看到下载后递归完成。
任何想法如何等待从递归 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 次
【问题讨论】:
-
你提供的代码会给你一个错误
'await' expression is only allowed within an async function -
谢谢。现在我很想在 stackblitz 中看到一个真实的例子,因为这段代码对我来说看起来不错
-
是的,已更正。
-
所以你有可用的 observables 并且你选择使用 Promise?为什么?
标签: javascript angular typescript for-loop recursion