Skip to content Skip to sidebar Skip to footer

How To Use Async Await In Nuxt.js?

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 consol

Solution 1:

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:

asyncfunctioncreated() {
  console.log('waiting...')
  awaitnewPromise(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:

exportdefault {
  methods: {
     // noSalir: async () => {...} ❌ don't use arrow functions hereasyncnoSalir() {...} ✅
  }
}

demo

Post a Comment for "How To Use Async Await In Nuxt.js?"