首页 > 解决方案 > 使用 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)
    });
}

标签: javascriptasynchronousasync-await

解决方案


它将以这种方式工作:

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

推荐阅读