在setTimeout中使用async有效吗? [英] Is using async in setTimeout valid?

查看:4009
本文介绍了在setTimeout中使用async有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Javascript中有一个异步函数,我添加了setTimeout。代码如下:

I had a asynchronous function in Javascript and I added setTimeout to it. The code looks like that:

        let timer;
        clearTimeout(timer);
        timer =setTimeout(() => {
        (async() => {
            await this._doSomething();
        })();
        }, 2000);

setTimeout的puprose是在运行函数前增加2秒。确保用户停止输入。

The puprose of setTimeout is to add 2 seconds before function will be run. It is to be sure that user stopped typing.

我现在应该从此函数中删除async / await,因为setTimeout是异步的吗?

Should I remove async/await from this function now, since setTimeout is asynchronous anyway?

这里的任何帮助非常感谢!

Any help here much appreciated!

推荐答案

setTimeout 添加延迟 之前的函数调用,而 async / 等待是承诺的语法糖,链接代码在 调用完成后运行 的方法,因此它们是不同的。

setTimeout adds a delay before a function call, whereas async/await is syntactic sugar ontop of promises, a way to chain code to run after a call completes, so they're different.

setTimeout has可怕的错误处理特性,所以我建议在所有代码中使用以下内容:

setTimeout has terrible error-handling characteristics, so I recommend the following in all code:

let wait = ms => new Promise(resolve => setTimeout(resolve, ms));

然后再不要再直接调用 setTimeout

and then never call setTimeout directly again.

您的代码现在变为:

let foo = async () => {
  await wait(2000);
  await this._doSomething();
}

除了 foo 等待用 doSomething 来完成。这通常是可取的,但没有上下文,很难知道你想要什么。如果您打算与其他代码并行运行 doSomething ,我建议:

except foo waits for doSomething to finish. This is usually desirable, but without context it's hard to know what you want. If you meant to run doSomething in parallel with other code, I recommend:

async () => { await Promise.all([foo(), this._otherCode()]); };

加入并捕获同一地点的错误。

to join and capture errors in the same place.

如果你真的想开火并忘记 _doSomething 而不是等待它,你可能会失去 await ,但你应该尝试/捕捉错误:

If you truly meant to fire and forget _doSomething and not wait for it, you can lose the await, but you should try/catch errors:

async () => {
  let spinoff = async () => { try { await foo(); } catch (e) { console.log(e); } };
  spinoff(); // no await!
}

但我不推荐这种模式,因为它很精致且很容易想念。

But I don't recommend that pattern, as it's subtle and can be easy to miss.

这篇关于在setTimeout中使用async有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆