Reputation: 35
Tried to make async
/await
work in Nuxt, but I don't know why it doesn't work anywhere.
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.
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>
Upvotes: 2
Views: 5956
Reputation: 138196
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.
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()
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() {...} ✅
}
}
Upvotes: 1