Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Mon May 15 2023

Difference between Promise and async await in JavaScript

In this article, we will show the difference between async await and Promise in JavaScript. We will also show some examples of how the two approaches can be used.

Differences

Async await and Promises are two ways of handling asynchronous code in JavaScript. Promise is the old school way of doing it, whilst async await is the more modern way of doing it.

Both approaches are based on the same idea basically, but the async await approach is more readable and easier to follow and to debug as well (if you ask me).

Promise

Let's honor the old way of doing it. In below example we will call an API and handle the response with promise chaining.

fetch("https://api.algobook.info/v1/city?search=paris") .then((response) => { response .json() .then((json) => { console.log(json); }) .catch((error) => { console.log(error); }); }) .catch((error) => { console.log(error); });

In above example, we are calling our free City API, and then we are handling the response with then and catch functions. If the call succeeds, it will call the then function, otherwise the error will be caught by the catch function. When our first then is called, we are doing an additional promise chaning since response.json() is also asynchronous.

Async await

Let's change approach and do it in the modern way and see if we can spot any difference in terms of readability :)

const fetchData = async () => { const response = await fetch( "https://api.algobook.info/v1/city?search=paris" ); const json = await response.json(); console.log(json); }; fetchData();

There we go. Less code and much more readable. The only thing to remember when using this approach, is that the function must be declared as async, otherwise we cannot use await operation. And making the function async will automatically change the return type to Promise<T>. Which means that if your function is returning a string, it will be Promise<string> if you make it async.

Example:

const myString = async () => { return "string"; }; console.log(myString()); // PromiseĀ {<fulfilled>: 'string'}

To get the return value, we need to await it

const myString = async () => { return "string"; }; const string = await myString(); console.log(string); // string

Outro

In this article we showed two different approaches on how to handle asynchronous code in JavaScript. Promise is the older way of doing it, and it has its benefits, such as you don't need to alter the functions to be be async if you want to use it e.g. And then the more modern way of doing it, with async/await approach which is much more readable and really handy.

Which one is your favourite?

Thanks for reading, and have an amazing day!

signatureMon May 15 2023
See all our articles