【问题标题】:how to wait for HTTP requests to get response in a loop before its processes to next step如何在处理下一步之前等待 HTTP 请求在循环中获得响应
【发布时间】:2021-06-06 16:56:29
【问题描述】:

如何等待 HTTP 请求获得响应。我尝试使用循环多次进行 API 调用,但我没有得到准确的数据,根据 API 调用的执行时间错误接收的值表示这些值,没有按照 request.required 的值比如 o,1,2,3,4 (index) 和它的返回值比如 2,1,3,4 来排列。

    var l=0 ; 
  for (var k=0;k<this.imagesdataarray.length;k++ ){

   this.http.post('http://api.interiordesigns2020.com/api/services/app/DesignerProject/Create',{
      name: this.imagesdataarray[k].projecttitle,
      designerCategoryID: this.imagesdataarray[k].categoryid,
      userID: this.userid
      
    })
    .subscribe(res => { 
   
        this.data1=res;
        this.imagesdataarray[l].projectid=this.data1.result.id;
        l++;
    }
    );
   
    } 

【问题讨论】:

    标签: javascript angular typescript angular8


    【解决方案1】:

    如果您想强制订阅块中的操作执行同步操作,您可以为订阅块中的匿名函数使用异步/等待模式。这是一个例子:

    .subscribe(async (res) => { 
    
        await this.data1=res;
        await this.imagesdataarray[l].projectid=this.data1.result.id;
        l++;
    });
    

    考虑到通话的完成是在订阅范围之外进行的,这可能仍然无法解决您的问题。我的建议是使用 rxjs 并尝试使用 forkJoin operator 构建一系列请求,然后从那里遍历每个订阅。

    【讨论】:

      【解决方案2】:

      你应该使用forkJoin() 来运行一个可观察的数组。

      以下是 StackBlitz 上的示例: https://stackblitz.com/edit/angular-ivy-t7phj1?file=src/app/app.component.ts

       array = [1, 2, 3, 4, 5];
      
        ngOnInit() {
          forkJoin(
            this.array.map(i =>
              this.http.get<any[]>(`https://jsonplaceholder.typicode.com/todos/${i}`)
            )
          ).subscribe(response => console.log(response));
        }
      

      【讨论】:

      • 这是我的做法,我上面的 async/await 答案可能行不通。
      猜你喜欢
      • 2019-06-29
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      相关资源
      最近更新 更多