Skip to main content

Promises and Asynchron calls in Metro Application and JavaScript

After I wrote this post I realize that I should write a post about promises in general. Because of this I wrote the following post.
The new Windows brought a new type of applications that are called Metro Applications. These applications are design to use fewer resources as possible and to be used very easily on tablets. Metro Applications can be written not only in XAML and C# but also in HTML5 and JavaScript. This is something new for Microsoft world; we can develop native application in JavaScript. Now JavaScript is a first-class citizen in Metro world.
Of course we cannot talk about Metro Applications without talking about asynchrony methods. We need this type of methods as we need water. When we make a call to a service or we want to write something to the disk we need these calls to be asynchronous.
The most used patterns for asynchronous calls in JavaScript is the callback pattern, where we specify as parameter the callbacks functions that will be called when the given actions ends. This pattern is very used in jQuery worlds.
Microsoft decides to use another well know standard for asynchron calls. The guys from Common/JS propose another standard that was adopted by Microsoft. The name of this standards is Promises/A and is very similar with how asynchronous task work on .NET 4.5. Also this standard is based on fluent pattern, because of this we can read and understand any code written more easily. If you already worked with Node.js, Ruby or jQuery 1.5 maybe you already used this standard without knowing.
Basically a promise represents a value that will be fulfilled in the future. The exact moment cannot be defined. In a Metro Application written in JavaScript any promise return an object that have two methods that are very important and similar – then and done.
promise.then(onComplete, onError, onProgress)
The then method have three parameters where we can specify the functions (handlers) that will be called when:
  • onComplete - the call end with success
  • onError – is called when during the execution of a code an error appeared
  • onProgress - a function that is called when the promise reports progress.
Of course we can omit any of the 2th a 3th parameter. The only one that is mandatory is the first one. The done function has the same signature as the then, the difference is the error handling. This function will throw any error that appeared in the call execution, in comparison with then function that will only return an error state.
Using these promises we don’t need to rely on anonymous functions that are defined inline. We can define functions in our code that can be specified in the then or done. When an error is thrown is more easily to detect the original location of the exceptions.
In Metro Applications all the Windows Runtime and Windows Library for JavaScript is defined using this standard. Because of this this knowing this standard is a have to and is not a nice to have (know).
fooWebService.get("http://www.microsoft.com")
.then(function(result) {
// process result
return fooWebService.get("http://windows.azure.com/")
})
.then(function(result) {
// process result
}
We can have as many then appended one after another. The condition is to have in each onComplete function to return another promise. If we don’t do this, the onComplete of the second then will be immediately called, without waiting the response of the first call.
The WinJS.Promise object defined by the framework came with some helper methods. Besides then and done functions the most important functions are:
  • join – create a promise that permits us to specify a list of promises and only when all this promises are fulfilled the onComplete is called.
  • any – create a promise that is fulfilled when one of the promises is fullfilled
  • wrap – wrap a non-promise function into a promise. It is very useful when we have a chain of promises.
For example we can use any to wait any specified promises from the list to be fullfiled. When one of them is fullfiled the callback is automatically caled.
WinJS.Promise.any([someMethod1Async(), someMethod2Async("someParam")])
.then(function() { console.log("done");});
Promises are not only defined by the system, we can also defined promises very easily. When we create a promise we need to create and return a WinJS.Promise object. The constructor accepts a function that has three parameters (the onComplete, onError, onProgress parameters). In the next example we defined a promise that wait for 10 seconds and call the complete function (this a one of the classic examples):
   function wait10SecondsAsync() {
return new WinJS.Promise(function (onComplete, onError, onProgress) {
var seconds = 10;
var intervalId = window.setInterval(function () {
seconds--;
onProgress(seconds);
if (seconds < 1) {
window.clearInterval(intervalId);
onComplete();
}
}, 1000);
});
}
In the end some small hints when working with promises:
  • always name suffix an asynchrone method with “Async”
  • when more than one promise are bound don’t forget to return the promises on each onComplete function
  • for the last call of an asynchrone chain call is recommended to use done and not then (done throws any exceptions to the upper code)
  • use WinJS.Promise.any and WinJs.Promise.wait when you need to wait for one or more promises
In conclusion promises are very powerful when we are talking about asynchrone calls in JavaScript language. When are used clevered, promises can help us not only to write beautiful cod but the code it almost writes by himself.

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP