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.

Understand the ASP.NET Core fundamentally (1)- Program.cs

Standard

Well, I gotta say, ASP.NET Core is definitely interesting. Thought it is s a bit late to discuss it now as this thing has been around for quite sometime. But if you are like me that late to this technology and intend to understand the fundamental, this article is right for you.

It is always a good idea to understand the basic structure of the file system and get the overall idea before using it in the first place. So I think it is necessary to understand those default files that generated while you create a new ASP.NET Core project. According to the MSDN documentation. These are the files and folders created by default:

  • Startup.cs : Startup Class – class configures the request pipeline that handles all requests made to the application.
  • Program.cs : Program Class that contains the Main entry point of the application.
  • [project_name].csproj : Project file MSBuild Project file format for ASP.NET Core applications. Contains Project to Project references, NuGet References and other project related items.
  • appsettings.json / appsettings.Development.json : Environment base app settings configuration file. See Configuration.
  • bower.json : Bower package dependencies for the project.
  • .bowerrc : Bower configuration file which defines where to install the components when Bower downloads the assets.
  • bundleconfig.json : configuration files for bundling and minifying front-end JavaScript and CSS assets.
  • Views : Contains the Razor views. Views are the components that display the app’s user interface (UI). Generally, this UI displays the model data.
  • Controllers : Contains MVC Controllers, initially HomeController.cs. Controllers are classes that handle browser requests.
  • wwwroot : Web application root folder.

The two most important files to discuss here are Program.cs & Startup.cs. 

Program.cs

The Program.cs has a Main() method that kicks off the entire ASP.NET Core process, when you launch a ASP.NET Core application, it starts from here. Think of .NET Core as a console application like an executable. The entire service and function are only activated when you launch the application which here is the starting point. Hence, within the Main() method in Program.cs, there are many steps for configuring and initializing web service related setup.

 public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

The Main() method instantiates the WebHostBuilder class to configure the .NET Core web server. You can tell from here that the WebHostBuilder is the main component that dictates the entire application configuration. It is using a builder pattern that step by step to create the IWebHost object by calling the build() method lastly. What builder pattern does is just creating a custom object with its own self-defined step by step process, you can find out more from builder pattern

So let’s take a look of these steps for building the web host IWebHost object.

First of all, you need to understand that the WebHostBuilder is an implementation of  IWebHostBuilder, it has many features that could expand into another post, but we only focus on the methods are shown in the code snippet.

First

UseKestrel()

After instantiate the WebHostBuilder , it first calls UseKestrel() to specify a default web server, this is the default ASP.NET Core cross-platform web server that listens all the HTTP requests and surfaces them to your application as set of request features composed into an HttpContext.

Next

UseStartup<Startup>()

The second step here, it calls the UseStartup() method by passing a Startup type class that defined in the Startup.cs file, which is another interesting file we need to explore later. The purpose of this method and the Startup class here can refer to the MSDN as follows

The Startup class is where you define the request handling pipeline and where any services needed by the app are configured.

So basically, define the request handling pipeline is for middleware and configure service needed is for dependency injection.

Build()
host.Run()

Finally, it calls the Build() method to return the IWebHost instant and this instant calls the method to kick off the web host server completely.

 

Conclusion

To summarize the ASP.NET Core launch process, we start from the Program.cs Main() method as an entry point, within the Main() method, we instantiate a WebHostBuilder object and configure the instant step by step for the web host server includes passing the Startup class that defines the request handling pipeline (middleware etc) and configures any services (dependency injection) needed by the app. Finally, the WebHostBuilder object run the Build() method to create another IWebHost instant which calls a Run() method itself to kick off the application host server.