Making a Promise: creating your own then() clause for async call with WinJS.Promise
WinJS introduces many convenience functions (still trying to learn them) to enrich the language. Some of them you'd see straight away even when just starting a Metro HTML5/Javascript application for Windows 8 like WinJS.Namespace etc. There are reasons to why you would not want to use these convenient functions. The biggest one would be the fact that WinJS is only available within the Windows 8 runtime. However putting that aside some of these functions are very valuable and easy to use. In this post I'm going to cover specifically on Promise.
What is it
WinJS.Promise is an implementation of CommonJS's Promise ecmascript spec proposal. The spec suggest that we should be able to do the following:
asyncComputeTheAnswerToEverything(). then(addTwo). then(printResult, onError);
Promise allows you to structure asynchronous code as if it was serial by chaining methods together : a technique that I'm sure you're familiar with by now through JQuery. To C# folks, this is the next best thing since we do not have async/await keyword for javascript.
How to implement a Promise with WinJS
In its simplest form here are the essential element to create a WinJS.Promise to be able to do the above:
(function () { "use strict"; // ... WinJS.Namespace.define("someNameSpace", { refreshAsync: function () { return new WinJS.Promise( function (completed, error) { try { //slightly long process ... // you could pass the result to the // completed function as arguments completed(); } catch (e) { error(); } }); } }); })();
then I could consume the method by:
someNameSpace.refreshAsync() .then(updateUI(), showUIError());
Tested on
Caveats, since all these things are still Beta, the above test ‘works on my machine’ with:
Windows 8 Consumer Preview
Visual Studio 2011 Ultimate Beta
Read more
constructing WinJS.Promise https://msdn.microsoft.com/en-us/library/windows/apps/br211866.aspx
constructing Done clause https://msdn.microsoft.com/en-us/library/windows/apps/hh701079.aspx
Saved me alot of time especially that there were no docs for defining promises on MSDN. Thanks!
thanks for dropping a comment too Yasser!!