Flattening callback pyramids

#Flattening callback pyramids

You’ve seen how chaining promises lets you flatten out a callback pyramid. But to really get an intuition for this, there’s no substitute for practice. So let’s do an exercise!

In the editor below, I’ve started you off with a working app that asynchronously fetches and displays some random numbers (simulating cryptocurrency prices). There’s just a problem: the app is built with callbacks.

Your task is to flatten the callback pyramid as much as possible by replacing callbacks with promises.

The provided getTicker(), getPrice() and writeLog() functions all use the error-first callback convention. This means that:

  • If an error occurs, it’ll be passed to the callback as its first argument.
  • If the functions complete successfully, the first argument will be null.

In order to flatten the callback pyramid, you’ll need to create three functions that mirror the existing functions, but return a callback instead of accepting a promise. These functions can be implemented with new Promise() — if you get stuck, I explain the process in more detail in the error-first callbacks lesson.


    One more hint: because writeLog() requires access to both ticker and price, you may find it a bit tricky to access both. If you get stuck here, you can click on this spoiler for some help:

    Using what you know, you can nest calls to then() within one success handler to return an array with ticker and price. You can then keep the rest of your callback pyramid flat.

    return getPricePromise(ticker).then(price => [ticker, price])

    I’ll go over another way to handle this scenario in the next lesson.

    Once you’ve given the exercise a solid try, compare your answer with mine by clicking the “Solution” button at the bottom of the editor. And once you’re ready, we’ll take a look at simpler approach to combining multiple promises.