Async/await
There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”. It’s surprisingly easy to understand and use.
Async functions
Let’s start with the async keyword. It can be placed before a function, like this: The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically. For instance, this function returns a resolved promise with the result of 1; let’s test it: …We could explicitly return a promise, which would be the same: So, async ensures that the function returns a promise, and wraps non-promises in it. Simple enough, right? But not only that. There’s another keyword, await, that works only inside async functions, and it’s pretty cool.
Await
The syntax: The keyword await makes JavaScript wait until that promise settles and returns its result. Here’s an example with a promise that resolves in 1 second: The function execution “pauses” at the line (*) and resumes when the promise settles, with result becoming its result. So the code above shows “done!” in one second. Let’s emphasize: await literally suspends the function execution until the promise settles, and then resumes it with the promise result. That doesn’t cost any CPU resources, because the JavaScript engine can do other jobs in the meantime: execute other scripts, handle events, etc. It’s just a more elegant syntax of getting the promise result than promise.then. And, it’s easier to read and write. function f() { let promise = Promise.resolve(1); let result = await promise; // Syntax error Let’s take the showAvatar() example from the chapter info:promise-chaining and rewrite it using async/await: 1. We’ll need to replace .then calls with await. 2. Also we should make the function async for them to work. Pretty clean and easy to read, right? Much better than before. // we assume this code runs at top level, inside a module let response = await fetch(‘/article/promise-chaining/user.json’); let user = await response.json(); console.log(user); (async () => { let response = await fetch(‘/article/promise-chaining/user.json’); let user = await response.json(); … })(); class Thenable { constructor(num) { this.num = num; then(resolve, reject) { alert(resolve); // resolve with this.num*2 after 1000ms setTimeout(() => resolve(this.num 2), 1000); // () async function f() { // waits for 1 second, then result becomes 2 let result = await new Thenable(1); alert(result); f(); class Waiter { async wait() { return await Promise.resolve(1); new Waiter() .wait() .then(alert); // 1 (this is the same as (result => alert(result)))
Error handling
If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. This code: …is the same as this: In real situations, the promise may take some time before it rejects. In that case there will be a delay before await throws an error. We can catch that error using try..catch, the same way as a regular throw: In the case of an error, the control jumps to the catch block. We can also wrap multiple lines: If we don’t have try..catch, then the promise generated by the call of the async function f() becomes rejected. We can append .catch to handle it: If we forget to add .catch there, then we get an unhandled promise error (viewable in the console). We can catch such errors using a global unhandledrejection event handler as described in the chapter info:promise-error-handling. // wait for the array of results let results = await Promise.all([ fetch(url1), fetch(url2), … ]);
Summary
The async keyword before a function has two effects: 1. Makes it always return a promise. 2. Allows await to be used in it. The await keyword before a promise makes JavaScript wait until that promise settles, and then: 1. If it’s an error, an exception is generated — same as if throw error were called at that very place. 2. Otherwise, it returns the result. Together they provide a great framework to write asynchronous code that is easy to both read and write. With async/await we rarely need to write promise.then/catch, but we still shouldn’t forget that they are based on promises, because sometimes (e.g. in the outermost scope) we have to use these methods. Also Promise.all is nice when we are waiting for many tasks simultaneously.
async function f() {
return 1;
}
Follow the lesson from Microsoft Web-Dev-For-Beginners course