Escape callback hell now with Promises in ES6! They’re supported in all major browsers and basically look like this:
1 | //basic syntax |
for further demonstrations let’s create a mockup request function we can pass a desired amount of seconds parameter to. This will simulate an asynchronous operation and resolve after the specified time.
1 | let Api = { |
Sequential
now since our requestSomething
function returns a promise, we can chain promises in a slick syntax like this:
1 | //chained promises |
Sequential chained Promises can be useful if a request 1s response gives us information about what we want to request 2 to look like.
Parallel
This doesn’t bring any significant advantage over callbacks yet but let’s check out Promise.all
1 | let promises = [ |
Promise.all
returns a new promise which will resolve after all the promises we passed it have resolved. The value
that gets passed into the .then
function is an array of all the resolve values from the initial requests.
what an awesome syntax to keep things clean and readable :)
Endnote
Notice that I always assumed that my requests will never fail. in real life specify a function in .then
that handles a failed request like this:1
promise.then(successFunction, failFunction)