javascript - 我是否需要在异步函数中的每个语句之前放置await?

标签 javascript asynchronous async-await es6-promise

我有一个异步函数,其中有些事情似乎在其他事情乱序之前执行。我认为这是因为我正在使用异步函数。但我怎样才能让它以正确的顺序执行(按照它的编写方式?)。我需要在每个这样的语句之前放置 await 吗?

或者我的语法不正确?

async foodDelivered(order_id, table_id)
{
    await let tmp_order_id = order_id
    await let deliveryTime = 0

    await this.btnDeliveredLoading = true

    await const index = store.table_timers.findIndex(({ order_id }) => order_id === tmp_order_id)

    await if (index != -1) {
        // Stop timer
        await clearInterval(store.table_timers[index].interval)

        // Remove timer
        await store.table_timers.splice(
            store.table_timers.findIndex(({ order_id }) => order_id === tmp_order_id), 1
        )

        await deliveryTime   = store.table_timers[index].time
    }

    try {

        await OrderHistory.updateColor({
            order_id: order_id,
            table_id: table_id,
            action: 'FOOD_DELIVERED',
        })

        // Save delivery time
        await OrderHistory.saveDeliveryTime({
            deliveryTime:   deliveryTime,
            order_id:       order_id,
        })

        // Refresh
        await OrderHistoryClass.getTotalOrderHistory({
            date: moment().format('YYYY-MM-DD'),
        })

        let tables = await Data.getTables()
        await store.tables = tables.data

        await this.drawerOpened = false
    }

    await this.btnDeliveredLoading = false
},

最佳答案

仅在预期返回 promise 返回的语句中使用await,象征着等待直到返回 promise 。因此,不是在每条指令中,而是在您需要的地方。

关于javascript - 我是否需要在异步函数中的每个语句之前放置await?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59532273/

相关文章:

javascript - 如何等待 module.export 函数完成请求,然后再将其返回值分配给不同 JS 文件中的变量

c# - 异步方法中的 StringBuilder

javascript - 在 Razor View 页面中使用 C# 对象

ios - 从 Swift 函数中的异步调用返回数据

javascript - 仅在 blogger/blogspot 的标签搜索页面上显示小部件

asynchronous - F#:异步下载数据

javascript - 使用 Node.js 同步写入时出错

c# - 如何从 .NET 4.5 中的并行任务中产生

javascript - 不使用 Flash 实现与 ctrl+c 相同的 ctrl+x 行为

javascript - 对 JavaScript 语法感到困惑