Async/Await: The Easy Way to Fetch

Brian Rhodes
JavaScript in Plain English
3 min readJul 20, 2021

--

Photo by Tudor Baciu on Unsplash

To understand Async/Await you first have to understand what promises are and how they work:

JavaScript is single threaded, meaning that two bits of script cannot run at the same time; they have to run one after another. A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. — freecodecamp.org

To start, Think of a promise like a callback function that runs asynchronously within your JavaScript code. It does not have to wait on other code nor does other code have to wait on it. It executes independently on its own. It is used for when you need to do something that will take a long time in the background and you want to do something right after it is complete instead of making everything else wait.

I think it is best to explain promises in a practical sense rather than doing what most tutorials will do:

Here we have a function that is supposed to “load images” by fetching them from a URL assigned to a variable (IMG_URL). After “fetching” those images it returns a promise containing a response. The tricky part is figuring out how .then() works.

.then() returns a promise as well. It takes two arguments: callback functions for the success and failure cases of the Promise. The variable labeled r is the response of the initial fetch which is the previously completed promise.

as shown here:

Lets change console.log(r) to console.log(r.json()) . If you refresh the page you with see this in the console :

realize it says “Promise {<pending>}”. Now lets remove the console.log from console.log(r.json()) and refresh the page again. We fulfilled the promise and now we get an object which we labeled as “data”

From here you can implement a callback function to manipulated the data by using “data” as the argument:

Now that we somewhat understand promises and responses let's refactor that same chunk of code with Async/Await syntax:

The async keyword lets javaScript know that the function is supposed to be run asynchronously. The await keyword is basically saying “wait until the following code is finished THEN execute the next thing”. This is exactly the same thing as we have been doing before, with just a little syntactical sugar added. It is important to have a basic understanding of fetch and .then() before delving into Async/Await.

Hope this helps.

More content at plainenglish.io

--

--

Software Developer | Writer at 𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵 𝘐𝘯 𝘗𝘭𝘢𝘪𝘯 𝘌𝘯𝘨𝘭𝘪𝘴𝘩 | Written easy-to-understand explanations for myself and others.