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



我有一个向前导航函数,它在某些阶段触发异步API调用,在该阶段需要它不继续(向前移动),直到所述API调用完成(它触发后续阶段所需的后台处理器)。

我的问题是,它继续进行,尽管呼叫尚未完成。我对实现这一点的最佳和最建议的方法感到困惑,并将很高兴得到任何建议。

代码:

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();
},

如何调用goNext函数:

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

在呼叫中也使用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();
},

相关内容

  • 没有找到相关文章

最新更新