如何在 Nuxt.js 中使用异步等待? [英] How to use async await in Nuxt.js?
问题描述
试图让 async
/await
在 Nuxt 中工作,但我不知道为什么它在任何地方都不起作用.
Tried to make async
/await
work in Nuxt, but I don't know why it doesn't work anywhere.
在created
钩子中,它不会等待setTimeout
,而是激活第二个console.log()
.在methods
中,除了setTimeout
跳过它外,它不识别this
.
In the created
hook, it just doesn't wait for the setTimeout
, and activates the second console.log()
. In the methods
, it does not recognize the this
in addition to the setTimeout
skipping it.
谁能给我一个例子,说明它应该如何正确拼写才能工作?我正在使用 Nuxt.
Can someone give me an example of how it should be spelled correctly for it to work? I'm using 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
only awaits a Promise
or an async
call (which resolves to a Promise
). When you await
anything other than a Promise
, it returns immediately. Since setTimeout
does not return a Promise
(it returns a timer ID), the await
call on that line returns immediately.
要使 await
实际上等待 setTimeout
完成,请将其包装在 Promise
中:
To make that await
actually wait for the setTimeout
to complete, wrap it in a Promise
:
async function created() {
console.log('waiting...')
await new Promise(resolve => setTimeout(() => {
console.log('hola')
resolve()
}, 1000))
console.log('adios')
}
created()
关于你的方法中错误的 this
,问题是你已经将它声明为一个箭头函数,它捕获了外部的 this
(undefined
代码>在证监会).要确保正确的 this
上下文,请在此处使用常规函数:
Regarding the wrong this
in your method, the problem is you've declared it as an arrow function, which captures the outer this
(undefined
in an SFC). To ensure the correct this
context, use a regular function here:
export default {
methods: {
// noSalir: async () => {...} ❌ don't use arrow functions here
async noSalir() {...} ✅
}
}
这篇关于如何在 Nuxt.js 中使用异步等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!