Asynchronous Programming in JavaScript: Promises

in #javascript6 years ago (edited)

JavaScript is a single-threaded programming system. However, a lot of tasks are performed asynchronously by the host environment. Async tasks do not follow the ordinary flow of the program, because it is not determined when they will be resolved or if they will encounter an error.

For doing an async task, you need to use a callback function in the very least. However, if you are going to do several async tasks in tandem, your nested callbacks will soon make the program unreadable or unmaintainble. This is where promises come in.

A promise is an object with a then method that is called when an async task has been resolved or rejected.

In order to create a promise, you can use the Promise constructor. For example:

    let promise = new Promise((resolve, reject) => {
        try {
            let result = asyncTask();
            resolve(result);
        } catch(e) {
            reject(e);
        }
    })

The promise has a then method that accepts two parameters:

    .then(onResolve, onReject)

If the promise is resolved, the onResolve handler is called with the result. If there was an error, the onReject handler is called with the reason of rejection.

There is also a catch method that handles only the rejection cases:

    .catch(onReject)

On the other hand, the promise has also a finally method with a handler that is called after the promise has been either resolved or rejected:

    .finally(handler)

Promises are especially useful for chaining several async tasks:

    Promise.resolve(a)
    .then(a => asyncTaskA(a))
    .then(b => asyncTaskB(b))
    .then(c => asyncTaskC(c))
    .catch(e => console.log(e))
    .finally(() => cleanUp());

The promises make an elegant solution for dealing with async tasks. However, there is a newer method for this purpose, namely the async and await keywords, that I will discuss in the next post.

Sort:  

What is really interesting about promises (comparing to ordinary callback approach) is that you, as a developer, have a flow under your control. Within the callback you basically send your function reference to third party library, i.e.:

api.sync(cb)

Now imagine, your cb function does sensitive data manipulation, even money transfers. So, are you 100% sure, that third party lib will call your callback only once? Perhaps it will be twice or more? Promises gives you some kind of inverted approach. You basically do not send the callback to third party library, so the whole flow is managed by you, only. What the library only does is call resolve or reject with operation result (as you provided in your example). They literally can't access your cb function reference, to call it twice or even more.

What's more, Promises are designed in such way, that they must be called only once.

PS: Great article. You might also take a look on the Observables, as you are touching async flow management in your posts. Cheers.

Thank you, @adasq. You have provided good insights. I wrote a pub/sub module a few years back and I have been using it frequently, but I am not much familiar with observables. I'll have to read about it.

script>

var ghasemkiani = "Really helpful dear keep it up";

alert(ghasemkiani);

</script

Bisyar khub aghai Ghasim.

I am trying to learn java programming. So you posts and examples will help me a lot. Thank You.

Al are informative

All information are beyond my understanding. Seems like I have nothing to comment about here. Sir! when will you return back posing idioms :)

I have decided to explore other topics. I will probably have other language-related posts in the future.

I try to learn javascript.

JavaScript is really an interesting language. With it, we can create a very cool stuff. Have you ever tried JavaScript? @ghasemkiani

probably we are going to learn JavaScript

thanks for sharing i want to learn javascript

Coin Marketplace

STEEM 0.18
TRX 0.14
JST 0.029
BTC 57382.38
ETH 3075.07
USDT 1.00
SBD 2.39