【问题标题】:Await a recursive For loop in Angular 8等待 Angular 8 中的递归 For 循环
【发布时间】: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


【解决方案1】:

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

Using an async function in Array.find()

【讨论】:

    猜你喜欢
    • 2023-01-20
    • 2020-08-11
    • 1970-01-01
    • 2019-03-01
    • 2018-06-09
    • 2018-01-06
    • 1970-01-01
    相关资源
    最近更新 更多