简体   繁体   English

在循环内使用 Async Await

[英]Using Async Await inside loops

I have encountered a problem where i have to send some JSON data stored in an array to the server.我遇到了一个问题,我必须将一些存储在数组中的 JSON 数据发送到服务器。 The problem is loop just run to the next iteration without waiting to get response from the server.问题是循环只是运行到下一次迭代,而无需等待服务器的响应。 I Don't want to use Time out Cause i can not preJudge the response time of the server.我不想使用超时因为我无法预先判断服务器的响应时间。

 async  uploadResponces(responseList) {
var idList = responseList;

for (let i = 0, j = 1; i < idList.length; i++ , j++) {
  var newArray = JSON.parse(idList[i].response)

  await this.apiConnect.postResponseTwo('submitform', newArray).then((data) => {
    self.submitStatus = data;
    alert(JSON.parse(this.submitStatus))
    if (this.submitStatus.status == "success") {
      alert(idList[i].id)
      var topush = JSON.stringify(idList[i].id)
      this.submited.push(idList[i].id)
      if (j == idList.length) {
        alert("submited array" + this.submited)
        this.deleteresponse()
      }
    }
  }).catch((errr)=>alert(JSON.stringify(errr)))
 }
}

the apiconnect.postResponseTwo is- apiconnect.postResponseTwo 是-

postResponseTwo(endpoint: string, body: any, reqOpts?: any) {
return new Promise((resolve, reject) => {
  console.log("post responce function");
  let httpHeaders = new HttpHeaders({
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, DELETE, PUT',
    'Access-Control-Allow-Headers': 'Accept,Accept-Language,Authorization,Content-Language,Content-Type',
    'Access-Control-Expose-Headers': 'Content-Length,Content-Range',

  });

  reqOpts = {
    headers: httpHeaders
  };
  let getURL = this.formUrl + endpoint;
  alert(endpoint + reqOpts);
  alert("url " + getURL);
  alert("passing object " + body);
  this.http.post(getURL, body, reqOpts).map((data) => {
    resolve(data)
    // alert("from server " + JSON.stringify(data));
    //  alert(JSON.stringify(data))

  }, err => {
    alert("error " + JSON.stringify(err));
  })
 });
}

here the function postResponse is sending data to the server inside a loop but if(j==idList.length){ is not waiting to get the response from server .这里的函数 postResponse 正在循环内向服务器发送数据,但if(j==idList.length){不等待从 server 获得响应。

If .subscribe really returns a promise then you should definitely use Promise.all instead of a loop.如果 .subscribe真的返回一个 promise,那么你绝对应该使用 Promise.all 而不是循环。 All promises are invoked at the same time and run in parallel.所有 Promise 同时调用并并行运行。 Promise.all is resolved only when the last promise in the given array is resolved. Promise.all 只有在给定数组中的最后一个 promise 被解析时才会被解析。 Due to parallel execution it's a way better solution than running a loop – unless you depend on execution order, but then you'd need to chain your promises and would not be able to loop anyway.由于并行执行,它是比运行循环更好的解决方案 - 除非您依赖执行顺序,但是您需要链接您的承诺并且无论如何都无法循环。

So, first create an array of promises kind of like this (I have not tested this code, so it might contain typos):所以,首先创建一个类似这样的承诺数组(我没有测试过这段代码,所以它可能包含拼写错误):

// create an array of promises
const responsePromises = map((idItem) => {
  const newArray = JSON.parse(idList[i].response);
  return this.apiConnect.postResponse('submitform', newArray).subscribe((data) =>
  {
     // whatever needs to be processed here
  });
});

// execute promises in parallel either:
Promise.all(responsePromises)
  .then(results => {
    // result handling
  })
  .catch(err => {
    // error handling
  });

// or with async/await but then your enclosing
// function must be async
const results = await Promise.all(responsePromises);

Your question was not detailed and sufficiently specified, so my answer might not really match what you've hoped for.你的问题不够详细,也不够具体,所以我的回答可能与你所希望的不符。

You are mixing async/await and rx.您正在混合 async/await 和 rx。 You actually can do that (but you probably should not), since Observables have a toPromise() method, and you can await the resulting Promise.您实际上可以这样做(但您可能不应该这样做),因为 Observables 有一个toPromise()方法,并且您可以等待生成的 Promise。 But subscribe() does NOT return a Promise, it returns a Subscription.但是subscribe()不返回一个 Promise,它返回一个订阅。 A Subscription is used to unsubscribe, is no Promise and thus NOT awaitable.订阅用于取消订阅,不是承诺,因此不可等待。

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

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