ES6 brings a new way of handling event flow with the new promise object, this seems to be a huge addition to Javascript since it involves new ways of doing asynchronous computations, but what are asynchronous computations ? what are synchronous, and how do promises work, what do they do ? Come along and let’s figure it out.
See the Pen ES6 Sampler - Promises Pt. 1 by Eugenio - Keno - Leon (@k3no) on CodePen.
Great, so sequential operations are analogous to synchronous computations, that is things that happen one step at a time in order, asynchronous computations, on the other hand can happen independently from one another, in this case via a timeout function. So, I guess the next thing we might need to figure out, is why we need promises, I mean the previous example worked fine, why add new objects if they don’t serve a purpose.
See the Pen ES6 Sampler - Promises Pt. 2 by Eugenio - Keno - Leon (@k3no) on CodePen.
So it seems that promises were introduced to deal with the above 2 problems, callback Hell.- where it is easy to loose track of what happens where and the Pyramid of Doom which is just hard to write and maintain, so what do promises offer, how do they work ?
See the Pen ES6 Sampler - Promises Pt. 3 by Eugenio - Keno - Leon (@k3no) on CodePen.
Ahhh, so after a bit of trial an error, I think I got a handle on the basics of promises, you define them with reject (In case of errors) and resolve (in case everything went well) clauses, and then call them and use whatever they produce to control the flow of your program down stream, it seems a little like overkill, the syntax definitely gets some time to get used to, so let’s revisit our original premise and find out how to rewrite things with promises…
See the Pen ES6 Sampler - Promises Pt. 4 by Eugenio - Keno - Leon (@k3no) on CodePen.
The above mini sample hopefully exemplifies how promises make things a little more readable.
And how about Async computations ? surely this is where promises will be of use the most.
See the Pen ES6 Sampler - Promises Pt. 5 by Eugenio - Keno - Leon (@k3no) on CodePen.
So after all this preamble, the last thing I would like to do is figure out some real world examples:
See the Pen ES6 Sampler - Promises Pt. 6 by Eugenio - Keno - Leon (@k3no) on CodePen.
It takes a little getting used to, but anything that returns something after some time can probably be rewritten using promises, as to whether or not you want to, that is entirely up to you, but as other programmers take a liking to promises, you will encounter them in the wild, so it’s better to know how to spot them.
Promises seem to be a more robust and complex alternative to using callbacks to control the flow of your program,they take some getting used to, but are somehow clearer at displaying and managing complex asynchronous operations.
Promises are a sophisticated way of handling async & sync computations and the flow of operations within your program.
Best,
Keno.