Search code examples
javascriptwinjspromiseasynccallback

How to wrap callback-function to get promise in WinJS?


I wonder how I can achieve a conversion such as:

fn(args, function (errors, results) {})

to

fn(args).then(function (results){})

by simply calling something like

makePromise(fn, args).then(function (results))

in WinJS.

Background: I have a predefined interface using async callbacks, but I'd like to use them as a promise.

Is this possible in this way? Maybe even directly supported by WinJS?


Solution

  • No, I could not find such a method in the official docs. However, this should do it:

    function makePromise(fn, args) {
        return new WinJS.Promise(function init(completeDispatch, errorDispatch) {
            fn(args, function handler(errors, results) {
                if (errors)
                    errorDispatch(errors);
                else
                    completeDispatch(results);
             });
        });
    }