WinJS:从函数返回承诺

WinJS : Returning promise from a function

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

//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 中 return WinJS.xhr,但是 f1 的 done 方法会 return 请求而不是 "data".

几乎没有变化:

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

您确实不想 return WinJS.xhr() 本身,但您想要 return .then(…) 调用的结果,这正是承诺解析为回调的 return 值。这是 the main features of promises 之一 :-)