繁体   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