# Async Await

Async function is a function that returns Promise. The benefit is, it makes code more readable.

The goal of async is to make the code look synchronous, an asynchronous code look synchronous.

Async Await are just promises under neat the hood, we called it syntactic sugar.

```javascript
EX 1:
async function playerStart() {
    const firstMove = await move(400, 'Left');
    await move(400, 'Right');
    await move(400, 'Up');
    await move(400, 'Down');
}
```

```javascript
EX 2:
// Basic usage
fetch('https://jsonplaceholder.typicode.com/users')
    .then(res => res.json())
    .then(console.log);
    
// using ASYNC AWAIT
async function getUsers() {
    const res = await fetch('https://jsonplaceholder.typicode.com/users')
    const data = await res.json();
    console.log(data); // response
}
```

```javascript
EX 3:
const urls = [
    'https://jsonplaceholder.typicode.com/users',
    'https://jsonplaceholder.typicode.com/posts',
    'https://jsonplaceholder.typicode.com/albums'
];

// Basic usage
Promise.all(urls.map(url => {
        fetch(url).then(res => res.json());
    }))
    .then(array => {
        console.log('users', array[0]);
        console.log('posts', array[1]);
        console.log('albums', array[2]);
    })
    .catch(console.log);
    
// using ASYNC AWAIT
const getDatas = async function() {
    try {
        const [users, posts, albums] = await Promise.all(urls.map(url => {
            return fetch(url).then(res => res.json());
        }));
        console.log('users', users);
        console.log('posts', posts);
        console.log('albums', albums);
    } catch(err) {
        console.log(err);
    }
}
getDatas();
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascript-1.gitbook.io/javascript/async-await.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
