簡體   English   中英

我需要在異步函數中的每個語句之前放置 await 嗎?

[英]Do I need to put await before every statement in an async function?

我有一個異步函數,其中有些事情似乎在其他事情無序之前執行。 我認為這是因為我正在使用異步函數。 但是我怎樣才能讓它以正確的順序執行(它的編寫方式?)。 我是否需要在這樣的每個語句之前放置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 所以,不是在每條指令中,而是在你需要它的地方。

絕對你認為是錯誤的。你只需要在 async 函數之前添加await ,而不是每個語句。

async function logAsync(a) {
    return Promise.resolve(a);
}

function logSync(a) {
    console.log(a);
}

function combination() {
    // you only add await before async functions
    await logAsync("async 1");
    // this does not need await before
    logSync(1);
    logSync(2);
    logSync(3);
}

將整個塊包裝在 try catch 中,並在返回 Promises 的語句之前放置 await

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM