Skip to main content

Async Await

@serverSerrverlesskiy

There is a special syntax работы for working with promises called async / await.

Creating an asynchronous function

creature

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() { ... }
}

Stops

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

run

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()

Promise

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

Wait

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

code rewriting

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()

fetch error

Total

Conclusion

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.

EnglishMoji!

Problems?

Problem

Write to Discord chat.

Questions:

Question

Where does the async keyword go?

  1. Before the function declaration
  2. After the function is declared
  3. In the body of the function

What functions does await work in?

  1. Only in synchronous functions
  2. Only in asynchronous functions
  3. In any function

An asynchronous function is:

  1. This is the function which is defined by the keyword async
  2. This is a function that anticipates the use of the await keyword
  3. Both options are correct

The advantage of async / await is:

  1. Own code is locked
  2. Getting rid of the code from .then() blocks
  3. The need to wrap expected promises in an asynchronous function

What this code is:

let hello = async function () {
return hello()
}
hello()
  1. Synchronous function
  2. Arrow function
  3. 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.

EnglishMoji!

  1. Async-await
  2. How to master async / await in JavaScript with real examples
  3. Asynchronous programming with async / await

Contributors ✨

Thanks goes to these wonderful people (emoji key):


AlisaNasibullina


Dmitriy Vasilev

💵

Resoner2005

🐛 🎨