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();
But I do not recommend this template, as it is thin and easy to skip.
jib Aug 18 '16 at 20:42 on 2016-08-18 20:42
source share