If you know how the event loop mechanism works in JavaScript you know how it enables you to work with asynchronous events. You might also know how to refactor your code into separate functions to reduce the amount of nesting associated with a sequence of callback functions. If you work with web APIs you are probably familiar with the JavaScript request library, which is used to perform HTTP calls.
You can put these skills together to retrieve remote data through an HTTP request and work with the call response asynchronously. But in doing so you’ll probably notice that code has at least one pitfall: the logical order of declared functions is reversed. That makes the code hard to read and maintain.
With the node-fetch JavaScript library and Promise objects you can reduce nesting, known as the callback “Pyramid of Doom”, and organize your code in a more readable and logical order.
While this post focuses on how to improve the modularity and flow of your code with these tools, the previous posts in the series explain Promise objects in more detail:
Asynchronous JavaScript: Introduction to JavaScript Promises
Asynchronous JavaScript: Advanced Promises with Node.js
If you need to brush up on callbacks you can learn about them in the first post in this series, Asynchronous JavaScript: Understanding Callbacks.
Prerequisites
To accomplish the tasks in this post you will need the following:
- Node.js and npm (The Node.js installation will also install npm.)
You should also have a working knowledge of the core elements of JavaScript, including object constructors and anonymous functions. Read the first post in this series if you are not familiar with the JavaScript event model.
There is a companion repository for this post, available on GitHub.
Setting up the project
If you have completed the project from the Asynchronous JavaScript: Advanced Promises post you can continue with the code you wrote for that post. If you are familiar with the event loop mechanism, or want to start fresh, you can get the code from GitHub.
Clone the project by executing the following command-line instructions in the directory where you would like to create the project root directory: