javascript - 使用 Async/Await 控制操作顺序
问题描述
我试图想出一种方法来确保在触发另一个函数之前完成某个操作。在我的代码中,我触发了一个 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();
}
推荐阅读
- c++ - 需要帮助理解 C++ 类的语法
- android - 导航抽屉中的微调器
- windows - 如何使用 Powershell 查找、停止和禁用 Windows 服务
- html - 如何复制粘贴整个 HTML 页面而不浪费缩写的 src 链接?
- java - 关于 docs.oracle 类 LinkedList 的问题
- public-key - 使用 bitcoin-abc 从公钥获取比特币现金地址
- node.js - 如何使用 Express.js 和 Angular 修复护照 - twitter 登录的 CORS 错误?
- python - 如何分组/合并具有各种数据类型的数据框
- python - Python Flask_MYSQLDB 问题
- python - 转储 jsons 并在文件名中包含日期