2016-03-21 76 views
0

我想做一個函數返回一個承諾。該承諾將包含在該函數中進行的異步調用的數據。我希望它看起來像:WinJS:從函數返回承諾

//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方法會返回請求而不是「數據」。

回答

2

幾乎沒有改變:

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()本身,而是要返回.then(…)電話這正是與返回值解決了承諾的結果的回調。這是the main features of promises之一:-)