![](/img/trans.png)
[英]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.