Is using async in setTimeout valid?

I had an asynchronous function in Javascript, and I added setTimeout to it. The code is as follows:

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

The setTimeout student must add 2 seconds before the function starts. He must be sure that the user stops printing.

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

Any help here is much appreciated!

+16
javascript asynchronous settimeout ecmascript-2017
Aug 16 '16 at 12:37
source share
2 answers

setTimeout adds a delay before the function call, while async / await is the syntax sugar of ontop promises, the way to link the code to run after the call completes, so they are 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 again.

Your code will now look like this:

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

except foo waiting for doSomething complete. This is usually desirable, but without context it is difficult to understand what you want. If you want to run doSomething in parallel with other code, I recommend:

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

to combine and capture errors in the same place.

If you really wanted to shoot and forget _doSomething , and not wait for it, you can lose await , but you should try / catch errors:

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

But I do not recommend this template, as it is thin and easy to skip.

+37
Aug 18 '16 at 20:42 on
source share
 /* contrived example alert */ var foo = 'poo'; function setFoo(callback) ( setTimeout(function(){ foo = 'bar'; callback(); }, 100); ); setFoo(function() { alert(foo); }); 
-5
Aug 16 '16 at 12:43 on
source share



All Articles