【问题标题】:Why does await not ensure order of execution in a method?为什么 await 不能确保方法中的执行顺序?
【发布时间】:2020-01-03 09:15:51
【问题描述】:

您好,我有以下问题:

我在按下按钮时对服务器执行两个async 请求。 第一个async 调用实际上是对提交表单的javascript 本地方法的调用。
第二个async 调用是使用服务的post。 我不明白为什么第二个请求有时会在第一个请求之前发生:

declare function submit(id: string): any;

 @Component({
  selector: 'index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
  })
 export class IndexComponent implements OnInit {

 public viewComputers: Computer[] = null;
 public catalog: Catalog = null;

 constructor(private service: AnubisService) { }

 async refreshListAsync() {
     this.catalog = await this.service.getCatalogAsync(); //post call to a server
     this.viewComputers = this.catalog.computers.items;
  }

 async cbSubmitAsync() {
     var result = this.submit("clientForm");  --call to js submit form method
     await this.refreshListAsync();  //how can this happen before the first call 
 }
}

Javascript 调用

 function submit(id) {
        return new Promise((resolve, reject) => {
            var form = document.getElementById(id);
            form.onerror = () => {
                reject("could not post");
            }
            var xhr = new XMLHttpRequest();
            var action = form.getAttribute('action');
            var method = form.getAttribute('method');
            xhr.open(method, action);

            xhr.onload = function () {
                if (xhr.status == 200) {
                    resolve(xhr.response);
                }
                else if (xhr.status != 200) {
                    reject("Failed to submit form with status" + xhr.status);
                }
            }
            var data = new FormData(form);
            xhr.send(data);
        });
    }

服务后调用

public async getCatalogAsync():Promise<Catalog>{
    let route=this.BaseUrl+"/api/admin/get-catalog";

    try  {
      var data=await this.http.get<Catalog>(route).toPromise<Catalog>();

      return data;
    }catch(ex){
      return null;
    }
  }

我的问题是:在cbSubmitAsync 方法中,第二次调用如何在第一次调用之前发生,如果是这样,我如何将它包装在一个承诺中(我也尝试过等待submit,但无济于事)

【问题讨论】:

  • 您告诉过(我也尝试过等待提交但无济于事)这是什么意思?你的意思是var result = await this.submit("clientForm");cbSubmitAsync 方法中。如果是这样,我相信它应该有效
  • 我试过submitawait submit
  • 它应该只添加 await 就可以工作。我尝试了这个场景,它对我来说非常好,所以你能用你的问题创建 JSFiddle

标签: typescript asynchronous post promise xmlhttprequest


【解决方案1】:

您必须在cbSubmitAsync() 方法的第一行使用await,因为this.submit(..) 已经返回Promise

var result = await this.submit("clientForm");

function submit() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Waited 500ms.");
      resolve();
    }, 500);
  });
}

async function cbSubmitAsync() {
  console.log("start");
  await submit();
  console.log("finished.");
}
&lt;button onclick="cbSubmitAsync()"&gt;Submit&lt;/button&gt;

【讨论】:

  • 我也用await无济于事。
  • await 在该行是“等待”发生的先决条件。也许您的submit 方法中有另一个错误。尝试使用await 并调试代码。
  • @Nenad 默认情况下异步标志为真,无需通过。看这里developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…
  • @AminKodaganur 对,我在代码中搜索一些问题太难了。
  • 我相信它应该通过在提交调用时添加等待来工作
猜你喜欢
  • 2018-01-07
  • 2022-08-14
  • 2022-11-26
  • 2016-10-24
  • 2015-09-16
  • 2016-08-06
  • 2014-06-28
  • 2019-07-01
  • 2015-06-21
相关资源
最近更新 更多