Showing posts with label promise. Show all posts
Showing posts with label promise. Show all posts

Thursday, October 5, 2017

Javascript Promise chaining

Hi there here is the third post of Javascript/NodeJs callback.

We have an async task with Promise:

[gist https://gist.github.com/vanduc1102/d7c84cd605edf8d0faf1fb620556ba5f]

Create tasks function:

[gist https://gist.github.com/vanduc1102/d07c13973a4c3cda3973b12f6619f1b9]

Promise.all


execute all the promises at the same times, and resolve when all of the promises resolved

[gist https://gist.github.com/vanduc1102/8b85ee8ce42d23fb49ae9d165bb19794]

and reject when any of the Promise was rejected:

[gist https://gist.github.com/vanduc1102/09a90b3923ca1ba3d5d72630958e950a]

Promise.race


The Promise.race(iterable) method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.

[gist https://gist.github.com/vanduc1102/21ff8e6900ebfb1824c965fb1d654291]

Sequence Promises


Sometimes we need to do the jobs in sequences.
[gist https://gist.github.com/vanduc1102/5264a38f20f54d04360a191e53c5e7e3]

For promise functions with multiple parameters

[gist https://gist.github.com/vanduc1102/b15f3f2ff5733ebbc467464e96cdf2ea]

 

Online editor

https://repl.it/@vanduc1102/sequence-promises

 

 

Monday, October 2, 2017

Javascript Callback Hell and Promise

The last article with the callback, we use callback function to solve the issue with asynchronous in Nodejs/Javascript.
[gist https://gist.github.com/vanduc1102/5e2e7cea325e628ad91fa11f6170d7a1]

But life is not that easy; sometimes a task needs more effort to be done.
Let assumed our task splits into three tasks now:
[gist https://gist.github.com/vanduc1102/b63a58ef1751d231d9111339be09df46]

In other to finish a task we need a callback hell (http://callbackhell.com/):

[gist https://gist.github.com/vanduc1102/f679b6039afd1ba893b310ace5b93e87]

Gather all snippets together:

[gist https://gist.github.com/vanduc1102/b22979ea867d47777e413c0831402fef]

Result:

callbackHell.js

In reality, a task may need more and more sub-tasks, the nesting will be super crazy.

Now we speak about Promise. Let convert our simple task from callback to promise
[gist https://gist.github.com/vanduc1102/523f1ffb2dccb9cc80f49de2d79e5611]

And then we will use Promise chaining to solve the callback hell issue.

[gist https://gist.github.com/vanduc1102/0b03c51edd629f05e1ddec95c7a288a8]

The result:

callbackHellPromise

 

Conclusion: To be honest I don't see my example has a clear explanation about Promise over Callback Hell, but you have to trust me, you will see Promise very helpful later.