Explain javascript promise from .NET async/await perspective.

Standard

It is a real pain to learn a new language that has so many new concepts (maybe not new, but different terms) that are unfamiliar and different a lot with your current programming skill.

For me, in order to pick up a new language, I would spend few days to torture myself by reading all the tedious documentations, and curse about why those people created this to make our life so hard to learn few things from scratch but in fact their are very similar. And eventually, angrily. I accept my faith and look for the next language to repeat such process and randomly curse those same things again……(A fate you would never be able to escape as programmer).

And yes… promise is one of them. If you use javascript, sooner or later you have to deal with promise. Everything is javascript now. If you have been using strong typed language like .NET C#. You may find yourself struggling with such loosely typed language.  And there are so many implementations of promise that syntax are presenting differently. It makes people like me feel even harder to understand what the heck is this promise all about.

If you do a googling for promise. There are many posts are simply talking similarly for the same subject, but none of them could connect this concept well with your current knowledge. And other posts try to use fancy way to describe the concept but help very little to explain the interaction for people from different programming background.

So after banging my head for few hours. I realize that we can simplify such concept by referencing our familiar C# async/await to make our .NET fan boy life easier.

Let’s illustrate our wonderful async/await syntax here to start our discussion.

A typical async/await would be something like this:

async Task<string> SomeActionReturnString()
{
    var str="";
    //do some async work here.
   return str;
}

var result = await SomeActionReturnString();

Console.WriteLine(result);//Here would be whatever the string would be

From above, method

SomeActionReturnString 

would execute asynchronously and the control would return back to main thread before the entire method complete. Once the method is done. The thread will be back and value return to

 result

variable. We all know that how async is handled elegantly. So the point here is that such asnyc approach is what promise trying to achieve with the same result.

So next, we do the same thing in promise way and believe or not, this can be easily translated into javascript promise.
To use promise, we can use many implementation, I would use simple Promise object here to demonstrate. You can apply the same to bluebird or any other components.

var SomeActionReturnString = function()
{
    return new Promise((resolve, reject)=>{
         var str="";
         //do some work here.
         //If the process completed successfully.
         resolve(str);
         //else if something goes wrong
         reject(err);
    });
}

So to invoke this method. We use it as follow:


SomeActionReturnString()
.then(
    function(str){
        //consume the str result here
        //In fact the str argument here is the same as
        //.NET await return str
    },
    function(err)
    {
        //handle error here
    }
);

I bet you confuse as fxxk here now. What the heck does it got anything to do with .NET async/await !!!

Well, in the definition of

SomeActionReturnString 

We use this Promise object here. By using it, whatever wrapped within the curly braces ‘{}’ would be executed asynchronously. That is how the magic is done by using the Promise object.
But the thing here is, the two argument

(resolve, reject)

here could confuse you a lot. The truth is they are here for reason. That is, you don’t return value within the body of Promise directly (the str value), you return value through the first argument resolve , and throw error with second reject handler. Both of these to handlers will be passed to next tailed .then() block which explain further below.

After that the code execute asynchronously and is done. The code would return to the

then()

which has 2 handler functions in the parenthesis, the first handler receive the value from resolve which is the str (Wala, same as .NET await return). The second handler receive the value from reject for actual error message and error handling (similar to the catch from try/catch), if there is nothing wrong with the SomeActionReturnString then this handler would never be called.

Conclusion

In .NET, the result would be returned from the await syntax. In javascript Promise, the value is returned to the then() handler that tailed after the method. From that aspect, they are very similar. But there are additional stuff added in for javascript like making use of Promise object.
Fundamentally, they achieve the same goal to run the code asynchronously but handle differently.
So, embrace yourself for more challenges.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s