[英]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?我是否需要在这样的每个语句之前放置
await
?
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.仅在预期返回
Promise
符号的语句中使用 await,即等待返回Promise
。 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 函数之前添加
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.