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(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...