Tip 43: Retrieve Data Asynchronously with Promises

What is an asynchronous language?

JavaScript is an asynchronous language. That’s a big word for a simple concept. An asynchronous language is merely a language that can execute subsequent lines of code when previous lines of code aren’t fully resolved.

All right. Maybe that explanation wasn’t any more clear. Think about reasons why code may be blocked. You may be getting data from an API. You might be pulling data from the DOM or other source. You might be waiting for a user response. The common thread is you need some information to proceed, and it may take time to get it. If you want more examples, Peter Olson has a great breakdown of the differences between asynchronous and synchronous code.

The value of asynchronous languages is that if there are parts of your code that don’t require the delayed information, you can run the code while the other code is waiting. If you’re waiting for an API response, you can still respond to click methods on other elements or calculate values of other data sources. Your code doesn’t grind to a halt while waiting.

In later tips, you’ll work with API data specifically. In this tip, you’ll explore a reusable technique for working with asynchronous data: promises.

Using callbacks for asynchronous actions

Before promises, developers used callbacks to handle asynchronous actions. If you requested expenses from a data source, you’d pass a callback function as an argument. After the asynchronous data is returned—or resolved as it is often called—the function would execute the callback. The traditional example is a setTimeout() function that takes a callback and executes it after a certain number of milliseconds.

Use setTimeout() as a place holder for any action that doesn’t immediately resolve. For example, think about a function called getUserPreferences(), which would fetch data from an API and then pass that data to a callback.

Because Javascript is asynchronous, you can call other functions before and after the call to getUserPreferences() and they’d both resolve before getUserPreferences() executes the callback.

Example: Using setTimeout()

Get hands-on with 1400+ tech skills courses.