Asynchronous Programming in JavaScript: Promises

in javascript •  7 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.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
  ·  7 years ago (edited)

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.

  ·  7 years ago (edited)

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.

Try its really easy

ok bro.

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

well i am on php now but let see java too

You are doing good research and sharing it is useful for many.

Its nice and good steeming you shared That is interesting and helpful.

wow good infermation
thank you @ghasemkiani

w0o0ww. Good to see a programmer here. your logic is awesome. sure I am waiting for your next post. stay blessed <3

Following you

Its awesome steeming post @ghasemkiani

Thanks for this sharing technology news i like it..

informative post.. thanks for sharing

good post dear @ghasemkiani

very good post 👌👌

it's very helpful and useful post.
keep it up

This is wonderful and great explanation for everyone of us who are yet to understand these programming. thanks for the time.

Thanks for sharing this post..I appreciate your blog..

keep it up

Informarive post...

Good information and best post thanks sir @ghasemkiani .
Stay blessed

so informative post for me.
thanks for your post

👍👍👍

1119.jpg