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

编程入门 行业动态 更新时间:2024-10-28 20:25:40
本文介绍了如何在 Nuxt.js 中使用异步等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

试图让 async/await 在 Nuxt 中工作,但我不知道为什么它在任何地方都不起作用.

Tried to make async/await work in Nuxt, but I don't know why it doesn't work anywhere.

在created 钩子中,它不会等待setTimeout,而是激活第二个console.log().在methods中,除了setTimeout跳过它外,它不识别this.

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.

谁能给我一个例子,说明它应该如何正确拼写才能工作?我正在使用 Nuxt.

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"); thisprobante = !thisprobante; } } }; </script>

推荐答案

await 只等待 Promise 或 async 调用(它解析到 Promise).当你 await 不是 Promise 时,它会立即返回.由于 setTimeout 不返回 Promise(它返回一个计时器 ID),该行上的 await 调用立即返回.

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.

要使 await 实际上等待 setTimeout 完成,请将其包装在 Promise 中:

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()

关于你的方法中错误的 this,问题是你已经将它声明为一个箭头函数,它捕获了外部的 this (undefined代码>在证监会).要确保正确的 this 上下文,请在此处使用常规函数:

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() {...} ✅ } }

演示

更多推荐

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

本文发布于:2023-07-16 04:23:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117790.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Nuxt   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!