Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 等待角度为8的递归For循环_Javascript_Angular_Typescript_For Loop_Recursion - Fatal编程技术网

Javascript 等待角度为8的递归For循环

Javascript 等待角度为8的递归For循环,javascript,angular,typescript,for-loop,recursion,Javascript,Angular,Typescript,For Loop,Recursion,从递归for循环接收结果时出现问题。我正在做一个递归,为“myArray”获取“cars”和“ships”,但它并没有等待。因此,当我点击下载json时,json没有“汽车”和“船舶”。在控制台中,我看到递归在我点击下载后完成 有什么想法可以等待接收递归for循环的结果,然后才开始下载 myservice.ts---------------------------------------------------------------------- public async callData(

从递归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);
public async callData():Promise{
返回新承诺(异步(解析、拒绝)=>{
this.toDownload.myArray=等待this.loop(this.toDownload.myArray);
解决(此。toDownload);
});
}
专用异步循环(myArray:[]):承诺{
返回新承诺(异步(解析、拒绝)=>{
for(设i:number=0;i
}

在控制台中,如果在每个方法中放置console.log,您将看到如下内容:

一,

二,

三,


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

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


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


您提供的代码会给您一个错误
“wait”表达式只允许在异步函数中使用
谢谢。现在我想在stackblitz中看到一个真实的例子,因为我觉得这段代码不错,是的,更正了。!所以你有可观察的,你选择使用承诺?为什么?您提供的代码会给您一个错误
'await'表达式只允许在异步函数中使用
谢谢。现在我想在stackblitz中看到一个真实的例子,因为我觉得这段代码不错,是的,更正了。!所以你有可观察的,你选择使用承诺?为什么?