简体   繁体   English

在 Typescript 中使用 Async Await 设置响应数据

[英]Use Async Await to Set Response Data in Typescript

I am hitting my API five times with different request data and pushing all response to an array and using.map to map the response array to my original array to set data but it is not working correctly my response data show it is undefined.我用不同的请求数据击中我的 API 五次,并将所有响应推送到数组并使用.map 到 map 对我的原始数组的响应数组以设置未定义的数据,但它无法正常工作。

Mycode: Status is the request data I am hitting to API to get response and statusArray is the array I need to set the data from response. Mycode:Status 是我打到 API 以获取响应的请求数据,statusArray 是我需要从响应中设置数据的数组。

statusArray = [
{
status: "Submitted",
count: 0
},
{
status: "Approved",
count: 0
},
{
status: "Rejected",
count: 0
},
{
status: "Open",
count: 0
}

]; 
 arr;
 temp =[]; 
 status = ["Submitted", "Approved", "Rejected", "Open"];
 async sendToApi(){
    for(let val of this.status)
    {
     this.arr = await this.getdata(val);
    }
    console.log(this.arr);
     await this.resolveData(this.arr);
}
async getdata(status)
  {
    this._service.getStatusBasedCount(status).pipe(takeUntil(this._onDestroy))
    .subscribe(async res =>{
      if(res['err'] == 'N')
      {
       this.temp.push({status: res['dataType'], count: res['dataTypeValue']});
       return this.temp;
      }
      
    });
   
   
  }
  async resolveData(arr)
  {
    let data  = arr;
    console.log(data);
    this.statusArray=   this.statusArray.map((item, row) => {
      const found = data.find(
        element => item.status == element.status
      );
      return { ...item, ...found };
    });
    
  }

For me the return this.temp return value but when i assign it to arr and print it in console it get undefined.对我来说,返回 this.temp 返回值,但是当我将它分配给 arr 并在控制台中打印它时,它会变得未定义。 Can I know how to do this?我能知道怎么做吗?

I don't see the need for async/await here.我认为这里不需要 async/await。 It would serve better to restructure the array as an object and use Object.key() with RxJS forkJoin to trigger all the requests in parallel.最好将数组重组为 object 并使用Object.key()和 RxJS forkJoin并行触发所有请求。 It could then be piped in with RxJS map operator to transform the data.然后可以使用 RxJS map运算符将其输入以转换数据。

Try the following尝试以下

status = {
  "Submitted": 0,
  "Approved": 0,
  "Rejected": 0,
  "Open": 0
}

getData() {
  forkJoin(
    Object.keys(this.status).map(status => 
      this._service.getStatusBasedCount(status).pipe(
        tap(res => {
          if (res['err'] == 'N') this.status[res['dataType']] = res['dataTypeValue']
        })
      )
    )
  ).subscribe();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM