[英]Await for Action to finish with Async/Await in Nuxt.js (SPA, no SSR)
[英]How to use async await in Nuxt.js?
試圖讓async
/ await
在 Nuxt 中工作,但我不知道為什么它在任何地方都不起作用。
在created
鈎子中,它只是不等待setTimeout
,而是激活第二個console.log()
。 在methods
中,除了setTimeout
跳過它之外,它不識別this
。
有人可以給我一個例子,說明它應該如何正確拼寫才能工作? 我正在使用 Nuxt。
<script>
export default {
data() {
return {
comprobante: true,
};
},
async created() {
await setTimeout(() => {
console.log("hola");
}, 1000);
console.log("adios");
},
methods: {
noSalir: async () => {
await setTimeout(() => {
console.log("hola");
}, 1000);
console.log("adios");
this.comprobante = !this.comprobante;
}
}
};
</script>
await
僅等待Promise
或async
調用(解析為Promise
)。 當您await
Promise
以外的任何內容時,它會立即返回。 由於setTimeout
不返回Promise
(它返回一個計時器 ID),因此該行上的await
調用立即返回。
要讓await
實際上等待setTimeout
完成,請將其包裝在Promise
中:
async function created() { console.log('waiting...') await new Promise(resolve => setTimeout(() => { console.log('hola') resolve() }, 1000)) console.log('adios') } created()
關於您方法中的錯誤this
,問題是您已將其聲明為箭頭 function,它捕獲了外部this
(在 SFC 中undefined
)。 為確保this
上下文正確,請在此處使用常規 function:
export default {
methods: {
// noSalir: async () => {...} ❌ don't use arrow functions here
async noSalir() {...} ✅
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.