【问题标题】:How to use async await in Nuxt.js?如何在 Nuxt.js 中使用异步等待?
【发布时间】:2021-02-14 03:41:00
【问题描述】:

试图让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>

【问题讨论】:

    标签: javascript vue.js nuxt.js


    【解决方案1】:

    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,问题在于您已将其声明为箭头函数,该函数捕获外部this(SFC 中的undefined)。为确保正确的this 上下文,请在此处使用常规函数:

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

    demo

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 2021-10-22
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多