javascript 这里我遇到了一个问题,代码以异步方式执行,并且temp变量由undefined赋值

m0rkklqb  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(105)
for(let i of this.movieData.reviews){
          this.http.get("http://localhost:9000/getUserByUserId/"+i.userId).subscribe(async resp=>{
            this.user= await resp
            console.log(this.user)
          })
          this.http.get("http://localhost:9000/getReviewById/"+i.reviewId).subscribe(async resp=>{
            this.review=await  resp
            console.log(this.review)
          })
          this.temp={
                  "userdata":this.user,
                  "reviewdata":this.review
                }
                console.log(this.temp)
          this.moviereviews.push(this.temp)
        }

我想以同步的方式来做这件事,这样临时变量就可以用给定的数据初始化并追加到数组中

idfiyjo8

idfiyjo81#

使用forkJoin的示例(未测试):

forkJoin([
  this.movieData.reviews.map((review) =>
    forkJoin([
      this.http.get("http://localhost:9000/getUserByUserId/" + review.userId),
      this.http.get("http://localhost:9000/getReviewById/" + review.reviewId),
    ]).pipe(map(([userdata, reviewdata]) => ({ userdata, reviewdata })))
  ),
]).subscribe((data) => {
  this.moviereviews = data;
});

相关问题