Speccy
Speccy

Reputation: 694

WinJS : Returning promise from a function

I would like to make a function that returns a promise. That promise would contain the data of an asynchronous call made in the function. What I want it to look like :

//Function that do asynchronous work
function f1() {
    var url = ...
    WinJS.xhr({ url: url }).then(
    function completed(request) {
        var data = ...processing the request...
        ...
    },
    function error(request) {
        ...
    });
}

//Code that would use the result of the asynchronous function
f1().done(function(data) {
    ...
});

The only way I found to make this work is to pass a callback to f1 and call it when I have the data. Using callbacks though seems to defeat the goal achieved by promises. Is there a way to make it work like above? Also, I could return WinJS.xhr in f1, but the done method of f1 would return the request and not the "data".

Upvotes: 0

Views: 56

Answers (1)

Bergi
Bergi

Reputation: 664589

There's little to change:

function f1() {
    var url = …;
    return WinJS.xhr({ url: url }).then(function completed(request) {
//  ^^^^^^
        var data = …; // processing the request
        return data;
//      ^^^^^^^^^^^
    });
}

//Code that would use the result of the asynchronous function
f1().done(function(data) {
    …
}, function error(request) {
    … // better handle errors in the end
});

You don't want to return the WinJS.xhr() itself indeed, but you want to return the result of the .then(…) call which is exactly the promise that resolves with the return value of the callback. This is one of the main features of promises :-)

Upvotes: 2

Related Questions