Liga
Liga

Reputation: 3439

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

I have an async function where some things seem to execute before other things out of order. I think it is because I'm using an async function. But how can I make it execute in the correct order (the way it is written?). Do I need to put await before every statement like this?

Or is my syntax not correct?

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
},

Upvotes: 0

Views: 1080

Answers (3)

Marek Kamiński
Marek Kamiński

Reputation: 432

wrap whole block in try catch, and put await before statements that return Promises

Upvotes: 0

H S
H S

Reputation: 735

Use await only in a statement which is expected to return a Promise symbolising, that wait until the promise is returned. So, no not in every instruction, but in places where you require it.

Upvotes: 2

fengxh
fengxh

Reputation: 384

Absolutely what you think is wrong.You only need to add await before async functions,not every statement.

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

Upvotes: 1

Related Questions