This is a more elegant way of getting a promise result than using promise.then. We can now turn a function that would just be utilizing the fetch keyword into an async function and see how it differs in clarity.

function jsonData(url) {

return fetch(url)

.then(res => {

if (res.status == 200) {

return res.json();

} else {

throw new Error(res.status);

}

});

}



jsonData('non') /

.catch(alert); // Error: 404

This can be updated to the following async function using await.

async function jsonData(url) { // (1)

let res = await fetch(url); // (2)



if (res.status == 200) {

let json = await res.json(); // (3)

return json;

}



throw new Error(res.status);

}



jsonData('no-such-user.json')

.catch(alert); // Error: 404 (4)

Important to Note

You cannot use the await keyword inside a regular function. This will cause a syntax error. Await needs to be used only inside an async function.

Although we can now make our code look synchronous, it is important to keep in mind that the execution is still asynchronous! This is important to note because you can dramatically increase your execution time if used incorrectly. The two examples below display the correct way to utilize an async function. If we use await on each individual function, the JavaScript compiler will wait till the first function is resolved prior to executing the second function. The whole point of the event loop is to avoid blocking code like what is done in the first example. If we need to wait for multiple promises we can wrap them in a Promise.all and then use await prior to the promise keyword.

// This would be the bad way to do this as you are blocking b from running until the a function returns.

const makeSomething = async() => {

const a = await getSomething('apples')

const b = await getSomething('strawberry')

return [a, b]

} // This is how you would allow your functions to run simultaneously

const makeSomething = async() => {

const a = getSomething(‘apples’)

const b = getSomething(‘strawberry’)

const result = await Promise.all([a, b]) return result;

} // wrapping our fetch in a Promise.all would allow them to run concurrently.

let results = await Promise.all([

fetch(url1),

fetch(url2),

]);

Conclusion

Async / await allows us to write asynchronous code that reads like synchronous code. It allows for some nicer readability when working with promises! To recap inside a function marked as async, you are allowed to place the await keyword in front of an expression that returns a promise. When you do, the execution of the async function is paused until the promise is resolved.

References

Please checkout all of the material that was reviewed to write this blog. There is a lot of great material to learn more about this nice syntactic sugar approach to promises and asynchronous JavaScript.