Page 129 - JavaScript
P. 129
Chapter 8: Async functions (async/await)
Introduction
async and await build on top of promises and generators to express asynchronous actions inline.
This makes asynchronous or callback code much easier to maintain.
Functions with the async keyword return a Promise, and can be called with that syntax.
Inside an async function the await keyword can be applied to any Promise, and will cause all of the
function body after the await to be executed after the promise resolves.
Syntax
• async function foo() {
...
await asyncCall()
}
• async function() { ... }
• async() => { ... }
• (async () => {
const data = await asyncCall()
console.log(data) })()
Remarks
Async functions are a syntactic sugar over promises and generators. They help you make your
code more readable, maintainable, easier to catch errors in, and with fewer levels of indentation.
Examples
Introduction
A function defined as async is a function that can perform asynchronous actions but still look
synchronous. The way it's done is using the await keyword to defer the function while it waits for a
Promise to resolve or reject.
Note: Async functions are a Stage 4 ("Finished") proposal on track to be included in the
ECMAScript 2017 standard.
For instance, using the promise-based Fetch API:
async function getJSON(url) {
try {
const response = await fetch(url);
https://riptutorial.com/ 86

