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(

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provided a too