In the latest version of languages like TypeScript or ECMAScript you can use async
/await
constructs to write code that combines the clean structure of synchronous programming with the performance advantages of asynchronous code.
Take this as an example:
async function isAdmin() {
// Async IO request...
return false;
}
async function doSomething() {
if (await isAdmin()) {
console.log("Done");
} else throw new Error("Unauthorized");
}
doSomething();
It looks very clean. However, because of the synchronous look of the code it's not that difficult to forget to await
on some function invocation, thus writing things like this:
// ...
if (isAdmin()) {
console.log("Done");
} else throw new Error("Unauthorized");
which is dangerously wrong.
What's the rationale behind this choice, instead of awaiting all async functions by default and letting the programmer choose which operation to do asynchronously? Something like this made-up syntax:
var admin = isAdmin(); // wait isAdmin to return a result
async doSomething(); // call doSomething asynchronously
doSomething(); // call doSomething synchronously
var promise = async doSomething(); // Get the underlying Promise
await
in front of it, you can treat it as if it is returning the actual promised value.