gpt4 book ai didi

javascript - 使用 Async/Await 控制操作顺序

转载 作者:行者123 更新时间:2023-11-30 19:54:03 25 4
gpt4 key购买 nike

我正在尝试想出一种方法来确保某个 Action 在另一个函数被触发之前已经完成。在我的代码中,我触发了一个 API 请求来更新数据,然后我根据第一个请求的结果计算了一些其他值。

但是,我有时会遇到第一个请求在第二个函数触发之前无法完成的情况,因此数据最终会损坏且不同步。我一直在用第二个函数的超时来临时处理这个问题。但是,我想改用 async/await,因为它显然是处理此类问题的更好(且有保证)的方法——因为假设超时会起作用从来都不是一件好事,而实际上它可能不会起作用。

这是我目前拥有的:

private async moveRecord(stage) {
if (!this.customer || !this.selectedService) return;
let targetService = this.selectedService.service;
let staffStarted = await this.userAccessService.getTargetId();

this.clientMoveService.moveClientRecord(this.client._id, category, targetService, staffStarted);

setTimeout(() =>
{
this.getNextStageOperation();
}, 1000);
}

如何调整此代码以使用 async/await 仅触发 this.getNextOperation一旦第一个请求this.clientMoveService.moveClientRecord()完成了吗?

我可以简单地这样做吗?

private async moveRecord(stage) {
if (!this.customer || !this.selectedService) return;
let targetService = this.selectedService.service;
let staffStarted = await this.userAccessService.getTargetId();

await this.clientMoveService.moveClientRecord(this.client._id, category, targetService, staffStarted);

this.getNextStageOperation();
}

为了进一步说明,moveClientRecord()是一个通过套接字发出的请求,看起来像这样:

public moveClientRecord(clientId: string, category: string, service: string, staffStarted: string)
{
let args = { id: clientId, category: category, service: service, staff: staffStarted };
console.log('args: ', args);

API.service.cast({
eventName: `clients.updateStatus`,
args: args,
listener: function (data)
{
// Ignore if socket disconnects
if (data === 'disconnect' || data === 'error') return;

// Return true to stop event listener
return true;

}.bind(this)
});
}

最佳答案

它将以这种方式工作:

private async moveRecord(stage) {
if (!this.customer || !this.selectedService) return;
let targetService = this.selectedService.service;
let staffStarted = await this.userAccessService.getTargetId();

// must return a Promise
await this.clientMoveService.moveClientRecord(this.client._id,
category, targetService, staffStarted);

this.getNextStageOperation();
}

关于javascript - 使用 Async/Await 控制操作顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54206695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com