Lesson 31. Advanced promises
After reading lesson 31, you will be able to
- Create your own promises
- Wrap callback-based methods with promises
- Use and understand how to properly write nested promises
- Understand how error handling propagates in promise chains
In the previous lesson you learned the basics of promises. We’ll now take a more advanced look at creating new promises and converting asynchronous code to use promises. We’ll look at advanced error handling, using promises for multiple asynchronous calls, and other advanced usages.
Consider this
Sometimes you need to make multiple asynchronous calls to get the data you need. A piece of data relies on another piece of data, which relies on yet another piece of data. Yet all of these pieces of data must be fetched from different locations. Traditionally you would have to treat these as three different operations with three different error catchers. What if you could turn it into one single operation with one error catcher?
A promise is created by instantiating a new Promise object with a function argument, new Promise(fn). The function given to the promise should take two arguments itself. The first one is a function to resolve the promise, and the second is a function to reject the promise: