Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

javascript - Is using async in setTimeout valid?

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 terrible error-handling characteristics, so I recommend the following in all code:

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

and then never call setTimeout directly again.

Your code now becomes:

let foo = async () => {
  await wait(2000);
  await this._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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...