Javascript WinJS:从函数返回承诺

Javascript WinJS:从函数返回承诺,javascript,asynchronous,promise,winjs,winjs-promise,Javascript,Asynchronous,Promise,Winjs,Winjs Promise,我想做一个返回承诺的函数。该承诺将包含在函数中进行的异步调用的数据。我希望它看起来像什么: //Function that do asynchronous work function f1() { var url = ... WinJS.xhr({ url: url }).then( function completed(request) { var data = ...processing the request... ... }

我想做一个返回承诺的函数。该承诺将包含在函数中进行的异步调用的数据。我希望它看起来像什么:

//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) {
    ...
});

我找到的唯一方法是将回调传递给f1,并在我有数据时调用它。然而,使用回调似乎无法实现承诺所实现的目标。有没有办法让它像上面那样工作?此外,我可以在f1中返回WinJS.xhr,但f1的done方法将返回请求而不是“数据”。

没有什么可更改的:

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
});

实际上,您不希望返回
WinJS.xhr()
本身,但是您希望返回
的结果。然后(…)
调用正是通过回调的返回值解析的承诺。这是其中之一:-)

没有什么可以改变的:

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
});
实际上,您不希望返回
WinJS.xhr()
本身,但是您希望返回
的结果。然后(…)
调用正是通过回调的返回值解析的承诺。这是其中之一:-)