Asynchronous call, not again! It is so difficult to handle errors! Why my code is so ugly? There must be a better way! … Search no more! The answer is in a software abstraction known as “promise”. If you learn it today, you get not one, but two libraries to solve your both server and client needs for price of learning one!Let’s try to write some asynchronous code.
User must login in order to get data. Operations are asynchronous. To make it shorter, only first function is simulating
asynchronous call using setTimeout
, but you get the idea. Both functions could return errors:
If everything is ok data will be dumped on the console. First let's do it in callback (hell) style.
Let’s use our functions in callback style:
First problem is error handling. Notice from code above that for each function in chain we have one error-handling block. This is super simple example and has only two functions. People from TV commercial had much more!
Second problem is using result from previous function. Second function must be nested in success callback of the first one.
Shortly, in JS-land there are gangs of asynchronous calls roaming main event loop. To put some order in it we can apply software abstraction called promise.
Key idea is simple. Our function will not call callbacks. It will return a promise. Promises are objects, and you can pass them around. Somewhere in the future promise will be:
Let’s create Login and GetData as promise.
Now let’s use our promises:
If any promise in the chain fails, promises after will be skipped and .fail
will be executed.
We have one place .fail
to handle errors from any function in a chain.
We have .fin
code segment that will be always executed. Looks familiar? try -> catch -> finally
.
Promises are:
There is much more in promises libraries. For example you can spin all promises at once using all()
.
In example below we are using fcall()
to quickly create promise from value.
So promises are great! They merge different callback conventions into call/return/exception pattern.
Recommended library is Q. Q has correctly implemented “then” function to return new promise instead of altering state of existing one. Q module can be loaded as script tag (client side). For the server side it is available in npm as “q” package. Also it is available from NuGet as “Q”.
Now you have no excuse to stop this madness and start using promises!