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
},
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.
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);
}
将整个块包装在 try catch 中,并在返回 Promises 的语句之前放置 await
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.