Async Await
There is a special syntax работы for working with promises called async / await
.
Creating an asynchronous function
An asynchronous function⚙️ is defined by an asynchronous function expression⚙️. The basic function⚙️ looks like this:
async function foo() {
const value = await somePromise()
return value
}
We define a function⚙️ to be asynchronous using async
. This keyword can be used with any syntax for a function declaration:
// Function Declaration
async function foo() { ... }
// Function Expression
const foo = async function () { ... }
// Arrow function
const foo = async () => { ... }
// Class methods
class Bar {
async foo() { ... }
}
Once we have defined the function as asynchronous, we can use the await
keyword.
This keyword is placed before a promise call, it pauses the function until the promise is fulfilled or rejected.
Async
We have the keyword async
, which we put before the function declaration to make it asynchronous. An asynchronous function⚙️ is a function⚙️ that anticipates the use of the await
keyword to run asynchronous code.
Try typing the following in your browser console:
function hello() {
return 'Hello'
}
hello()
The function will return Hello
. Nothing unusual.
But what if we turn it into an asynchronous function⚙️? Try the following:
async function hello() {
return 'Hello'
}
hello()
The function call now returns a promise. This is one of the features of asynchronous functions⚙️ - they return values that are guaranteed to be converted to promises.
You can also create an asynchronous function expression, like this:
// Function Expression
let hello = async function () {
return hello()
}
hello()
You can also use arrow functions⚙️:
let hello = async () => {
return 'Hello'
}
All these functions⚙️ do the same thing.
To get the value of a completed promise, we can use the .then()
block:
hello().then(value => console.log(value))
… or even like this:
hello().then(console.log)
Thus, adding the keyword async
causes the function to return a promise instead of a value. It also allows synchronous functions to avoid any overhead associated with starting and maintaining await. Simply adding async
before the function⚙️ enables the JS engine to automatically optimize the code.
Await
The benefits of asynchronous functions⚙️ become even more apparent when you combine them with the await keyword. It can be added before any promise-based function⚙️ to make it wait for the promise to complete and then return the result. After that, the next block of code is executed.
You can use await
when calling any function that returns a promise, including the Web API
functions.
Syntax :
let response = await fetch('https://jsonplaceholder.typicode.com/users')
let data = await response.json()
console.log(data[0].name + ' and ' + data[2].name)
Error handling with try ... catch
If you want to add error handling, you have several options.
You can use a synchronous try ... catch
structure along with async / await
:
async function myFetch() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/users')
let data = await response.json()
console.log(data[0].name + ' and ' + data[2].name)
} catch (e) {
console.log(e)
}
}
myFetch()
The catch () {}
block takes an error object объект, which we named e
. Now we can output it to the console, this will allow us to get a message about where in the code the error occurred.
Let's purposefully create an error in url and look at the error output.
async function myFetch() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/sers')
let data = await response.json()
console.log(data[0].name + ' and ' + data[2].name)
} catch (e) {
console.log(e)
}
}
myFetch()
Total
Async / await
allows you to write asynchronous code that is easy to read and maintain. For six reasons why it is better to use it instead of promises read here.
Problems?
Write to Discord chat.
Questions:
Where does the async
keyword go?
- Before the function declaration
- After the function is declared
- In the body of the function
What functions does await
work in?
- Only in synchronous functions
- Only in asynchronous functions
- In any function
An asynchronous function is:
- This is the function which is defined by the keyword
async
- This is a function that anticipates the use of the
await
keyword - Both options are correct
The advantage of async / await
is:
- Own code is locked
- Getting rid of the code from
.then()
blocks - The need to wrap expected promises in an asynchronous function
What this code is:
let hello = async function () {
return hello()
}
hello()
- Synchronous function
- Arrow function
- Asynchronous function expression
In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.
Links:
- Async-await
- How to master async / await in JavaScript with real examples
- Asynchronous programming with async / await
Contributors ✨
Thanks goes to these wonderful people (emoji key):
AlisaNasibullina | Dmitriy Vasilev 💵 | Resoner2005 🐛 🎨 |