簡體   English   中英

如何在 Nuxt.js 中使用異步等待?

[英]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僅等待Promiseasync調用(解析為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM