# Async and await

  • Async/Await is just a syntax sugar built on top of promises
  • Async/Await makes code look and behave a bit more like synchronous code
  • It makes your code more readable and easier to understand and maintenance-friendly

IMPORTANT

Async/Await does not entirely replace promises, it's only a nicer way to get rid of the chained .then() handlers

# Use promises with Async/Await

  • Assume we have three promises and two regular (synchronous) function that have to be executed one after one, then the code lookt like this:
function makeRequest() {
    return promise1()
    .then((response1) => promise2())
    .then((response2) => regularFunction1())
    .then((data1) => promise3())
    .then((response3) => regularFunction2())
}
makeRequest();
1
2
3
4
5
6
7
8
  • Converting this to async/await:
    • Add the keyword async in front of the function that contains one or more asynchronous function
    • Add the keyword await in front of the asynchronous function (not before regular functions) and add the resolved response to a variable
async function makeRequest() {
    const response1 = await promise1();
    const response2 = await promise2();
    const data1 =  regularFunction1();
    const response3 = await promise3();
    regularFunction2();
}
makeRequest();
1
2
3
4
5
6
7
8

# User fetch() with Async/Await

A fetch() function can be written with Async/Await as stand-alone version:


 



 












async function fetchFunction() {
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error(`An error has occurred: ${response.status}  ${response.statusText}`); // check for errors
    }
    return response.json();
}

async function otherFunction() {
    try {
        const data = await fetchFunction();
        // process the data inside this function
        // ...
    } catch (error) {
        console.error(error);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  • Or as a function where you do something with the data inside te function itself:


 



 







async function fetchFunction() {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`An error has occurred: ${response.status}  ${response.statusText}`); // check for errors
        }
        const data = await response.json();
        // process the data inside this function
        // ...
    } catch (error) {
        console.error(error);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# Error handling

  • We can catch errors using try...catch just like in synchronous code

 





 
 
 



async function makeRequest() {
    try {
        let resovelved1 = await callPromise1();
        let resovelved2 = await callPromise2();
        let data1 =  regFunction1();
        let resovelved3 = await callPromise3();
        regFunction2();
    } catch (error) {
        console.error(error);
    }
}
makeRequest();
1
2
3
4
5
6
7
8
9
10
11
12
  • Or use the catch() methode on the function that calls the async function







 
 
 

async function makeRequest() {
    let resovelved1 = await callPromise1();
    let resovelved2 = await callPromise2();
    let data1 =  regFunction1();
    let resovelved3 = await callPromise3();
    regFunction2();
}
makeRequest().catch (error) {
    console.error(error);
};
1
2
3
4
5
6
7
8
9
10

# Examples

  • Let's refactor some examples from the previous chapters to Async/Await

# Asynchronous calculator

  • Open es6/asyncAwait/calculator.html and es6/asyncAwait/calculator.js
  • Compare the refactored code with the code from es6/promises/calculator.js

# Karaoke

  • Open es6/asyncAwait/karaoke.html and es6/asyncAwait/karaoke.js
  • Compare the refactored code with the code from es6/promises/karaoke.js

# Random words

  • Open es6/asyncAwait/random_words.html and es6/asyncAwait/random_words.js
  • Compare the refactored code with the code from es6/promises/random_words.js

# Fetch images

  • Open es6/asyncAwait/images.html and es6/asyncAwait/images.js
  • Compare the refactored code with the code from es6/fetch/images.js

# Fetch movie info

  • Open es6/asyncAwait/omdb.html and es6/asyncAwait/omdb.js
  • Compare the refactored code with the code from es6/fetch/omdb.js

# Belgian railway schedules (advanced)

  • Open es6/asyncAwait/irail.html and es6/asyncAwait/irail.js
  • Compare the refactored code with the code from es6/fetch/irail.js

# Weather app

const key = 'MBEqSqMMid8s9gsk2cO6lAaYABDX05aM';

const getCity = async (city) => {
  const base = 'http://dataservice.accuweather.com/locations/v1/cities/search';
  const query = `?apikey=${key}&q=${city}`;

  const response = await fetch (base + query);
  const data = await response.json();

  return data[0];
}

getCity('Stockholm')
  .then(data => console.log(data))
  .catch(err => console.log(err));

  const getWeather = async (id) => {
    const base = 'http://dataservice.accuweather.com/currentconditions/v1/';
    const query = `${id}?apikey=${key}`;
    
    const response = await fetch(base + query);
    const data = await response.json();

    return data[0];
  };
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Last Updated: 4/12/2021, 7:55:49 AM