简体   繁体   English

暂停函数调用,直到异步调用完成

[英]Pausing a function call until an async call completes

I have a forward navigation function, which triggers an async API call on certain stages, where it is required that it does not proceed (move forward) until said API call is finished (it triggers a processor in the background required for the following stages).我有一个前向导航功能,它会在某些阶段触发异步 API 调用,其中要求它在所述 API 调用完成之前不继续(向前移动)(它在后台触发后续阶段所需的处理器) .

My issue is that it continues to proceed, despite the call not yet being completed.我的问题是它继续进行,尽管通话尚未完成。 I'm confused at to the best and most suggested way to implement this, and would be happy for any advice.我对实现这一点的最佳和最建议的方法感到困惑,并且很乐意提供任何建议。

Code:代码:

 async postData(url = "", data = {}) {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });
},

forwardTicketId(ticketId) {
  const origin = new URL(window.location.href).origin;
  const addr = `${origin}/current_ticket_id`;
  this.postData(`${addr}`, {
    data: ticketId,
  });
},

goNext() {
  if (this.isRequiredStage) { # this needs to complete before anything else runs
    this.forwardTicketId(this.ticketId);
  }
  this.navGoNext();
},

How the goNext function is called: goNext 函数的调用方式:

    <div class="level-right">
      <TicketStepsNavButtons
        @goPrev="goPrev"
        @goNext="goNext"
      />
    </div>

Use await in the calls too.在调用中也使用await

 async postData(url = "", data = {}) {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });
  // you can return the response if you need it
  return response;
},

forwardTicketId(ticketId) {
  const origin = new URL(window.location.href).origin;
  const addr = `${origin}/current_ticket_id`;
  // return to chain the next promises, you can async/await instead if you don't care about the result
  return this.postData(`${addr}`, { 
    data: ticketId,
  });
},

async goNext() {
  if (this.isRequiredStage) { // this needs to complete before anything else runs
    // await here
    await this.forwardTicketId(this.ticketId); 
  }
  this.navGoNext();
},

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

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