Chaining Promises

Learn about the basics of the promise chain and find out the results of passing different arguments to the promise chain.

One elegant feature of promises is that they form a pipeline like in the functional composition we discussed in the Arrow Functions and Functional Style lesson. Since both then() and catch() return a promise, calls to these functions may be chained to apply a series of filterings and transformations. An example will help you appreciate this elegance.

fs library

In the example in No Thanks to Callback Hell, we used the fs library’s readFile() asynchronous method, which relied on callbacks. The fs-extra library provides a wrapper around the functions of the fs library. We will use this to read the contents of a file asynchronously, but this time, using promises instead of callbacks.

Wrapping Callbacks into Promises

fs-extra is a library that wraps the callback-taking fs library of functions into Promise-returning functions. This library works with only methods of fs, but what about your own legacy code or any third-party functions?

The bluebird library was designed for this purpose. You can create a wrapper around any callback taking function using this library. Although you can design new asynchronous functions to work with Promise’s, use a library like bluebird to alleviate the pain of using legacy asynchronous functions.

Get hands-on with 1200+ tech skills courses.