Javascript: Asynchronous Data & Promises Basics

Scott Espinosa
6 min readNov 20, 2020

--

Pinky swears are never meant to be broken

While I was at Flatiron School, something that was always confusing my was asynchronous Javascript. I always had a hard time working with the data and on a recent take home assessment, I was completely destroyed by this question. Concept wise, I’ve always understood that asynchronous functions are functions that are running, but do not hold up the rest of the program. Meaning, while one function is still processing, another function would still be able to run while that first one is still going. Examples of this are making requests/fetches to servers. On the reverse side, synchronous means that each operation is happening in order and nothing else can happen until that operation is complete.

Prior to the release of ES6, callbacks were used to handle asynchronous JavaScript. With the release of ES6, Promises were introduced and later “Async Await” was introduced as well.

Callback Functions

A callback function is a function that is passed into another function as an argument, which is then invoked inside the outer function to complete some kind of action. As a simple example below, we will append li tags to the DOM of some of my favorite TV shows. We’ll use setTimeout to mimic a call to the server.

index.js — script included in index.html
index.html

With the example below, a call is made to the server to getPosts, which only appends FRIENDS and Schitt’s Creek to the DOM. Superstore does not get appended because createPost runs one second after getPosts, so the data isn’t available. In order to do this asynchronously, we’ll see a callback within the createPost function:

index.js — callback function included in createPost()

The minor change we completed was to add a parameter of a callback function to createPost and invoking the callback function within it. Doing it this way, we ensure that a new post of a TV show is added to the array prior to getting all the posts. This results to the page below:

index.html using callbacks

Promises

In a bigger application, callbacks can get a little messy (leading to callback hell). To clean up the code, ES6 introduced promises to handle asynchronous operations. Once you learn them, they are easier to manage when dealing with multiple async operations in terms of code readability, flow of control definition, error handling, and handling of the async operations.

Promise States

A Promise has four states:

  1. Fulfilled — action related to the promise that succeeded
  2. Rejected — action related to the promise failed
  3. Pending — promise that has neither been rejected nor fulfilled
  4. Settled — promise that has been either rejected or fulfilled

Promises are created using the Promise constructor, which takes a callback function as an argument. This callback function will take two arguments, resolve and reject. Operations are performed in the callback function and if everything goes well, it will call resolve. If there’s an error, it will instead call reject.

Promise Consumers

Promises can be consumed by registering functions using .then() and .catch() methods.

  1. .then() is invoked when a promise is either resolve or rejected and can take two functions as parameters. The first function would execute if the promise is resolved and a result is received. The second would handle the error, but the method below would be a better choice to handle errors.
  2. .catch() is invoked when a promise is either rejected or some error has occurred in execution. It takes one function as a parameter, which handles errors or promise rejection.

For the example we are using above, we can adjust the createPost function to return a promise using what was just described about promises:

When createPost is invoked, a promise is returned. In the example above, we created a promise that would result in an error. Therefore, .catch() will run instead of .then() due to the error. As a result, we will get index.html below:

If the error did not occur, then we’d get the result below:

Promise.all()

There’s also a method called .all(), which takes in an array of promises and will return a single promise that resolves when all the promises passed in the array are resolved. The output of that will also be an array. This is advantageous because it would prevent stacking .then() on multiple promises:

index.js — Promise.all()
message logged to the console

If any of the passed promises are rejected, then .all() will result in an error:

index.js — promise3 will reject
message logged to the console

Async / Await

One more thing! Javascript also provides another functionality to make code asynchronous, which is through async / await. These are basically extensions of promises, but written in different syntax.

Async

This allows to write promises based code as if it was synchronous. It makes sure that a promise is returned and if it’s not, then will automatically wrap it in a promise which is resolved with its value.

Await

This is used to wait for the promise and can be only used within an async block. It makes the code wait until the promise returns a result and it only makes the async block wait.

Updating the example with the TV shows, the example can be rewritten as follows:

index.js — async/await

Conclusion

There’s still so much to learn about asynchronous code and how to work with error handling in them. I’ve only scratched the surface of this topic, but just gotta keep on learning. Regardless, Moira Rose knows best in this situation.

Moira Rose of Schitt’s Creek

Resources:

  1. “Async JS Crash Course — Callbacks, Promises, Async Await,” Traversy Media, accessed Nov 19, 2020, https://www.youtube.com/watch?v=PoRJizFvM7s
  2. “Callback Function,” MDN Web Docs — Mozilla, accessed Nov 19, 2020, https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
  3. “JavaScript | Promises,” Geeksforgeeks, accessed Nov 19, 2020, https://www.geeksforgeeks.org/javascript-promises/?ref=lbp
  4. “JavaScript | Promise.all() Method,” Geeksforgeeks, accessed Nov 19, 2020, https://www.geeksforgeeks.org/javascript-promise-all-method/?ref=lbp
  5. “Async/Await Function in JavaScript,” Geekforgeeks, accessed Nov 19, 2020, https://www.geeksforgeeks.org/async-await-function-in-javascript/?ref=lbp

--

--

Scott Espinosa

Software Engineer based out of the San Francisco Bay Area. Flatiron School graduate with 8+ years background in healthcare.