Why are await and async valid variable names?

Reserved keywords cannot be used as identifiers (variable names). Unlike most other special Javascript words (like those listed in the question, let, finally, …), await is not a reserved keyword, so using it as a variable name does not throw a SyntaxError. Why wasn’t it made into a reserved keyword when the new syntax came … Read more

try/catch blocks with async/await

Alternatives An alternative to this: async function main() { try { var quote = await getQuote(); console.log(quote); } catch (error) { console.error(error); } } would be something like this, using promises explicitly: function main() { getQuote().then((quote) => { console.log(quote); }).catch((error) => { console.error(error); }); } or something like this, using continuation passing style: function main() … Read more

How to “await” for a callback to return?

async/await is not magic. An async function is a function that can unwrap Promises for you, so you’ll need api.on() to return a Promise for that to work. Something like this: function apiOn(event) { return new Promise(resolve => { api.on(event, response => resolve(response)); }); } Then async function test() { return await apiOn( ‘someEvent’ ); … Read more

async/await always returns promise

Every async function returns a Promise object. The await statement operates on a Promise, waiting until the Promise resolves or rejects. So no, you can’t do console.log on the result of an async function directly, even if you use await. Using await will make your function wait and then return a Promise which resolves immediately, … Read more

Waiting for more than one concurrent await operation

TL;DR Don’t use the pattern in the question where you get the promises, and then separately wait on them; instead, use Promise.all (at least for now): const [value1, value2] = await Promise.all([getValue1Async(), getValue2Async()]); While your solution does run the two operations in parallel, it doesn’t handle rejection properly if both promises reject. Details: Your solution … Read more

Correct Try…Catch Syntax Using Async/Await

It seems to be best practice not to place multiple lines of business logic in the try body Actually I’d say it is. You usually want to catch all exceptions from working with the value: try { const createdUser = await this.User.create(userInfo); console.log(createdUser) // business logic goes here } catch (error) { console.error(error) // from … Read more

Combination of async function + await + setTimeout

Your sleep function does not work because setTimeout does not (yet?) return a promise that could be awaited. You will need to promisify it manually: function timeout(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function sleep(fn, …args) { await timeout(3000); return fn(…args); } Btw, to slow down your loop you probably don’t want … Read more

tech