你不能在那個地方作爲實際值返回它,因爲Restangular
是異步的(在調用then
的回調被調用之前,功能getSlices
被留下)。這就是爲什麼使用Promise
。
即使有可能使Restangular
同步,您也不應這樣做,因爲這會阻止瀏覽器,直到數據被請求,這將是一個糟糕的用戶體驗。
您應該嘗試進入Promise
,因爲它們設計爲看起來像同步代碼但行爲異步。
你需要在你的代碼改變世界的事情是增加一個return
前Restangular.all
:
service.getSlices = function() {
return Restangular.all('entries').getList().then(function(entries) {
//some rather complex modification of the backend data go here
//...
return resultOfModification; //this is what should be returned for getSlices();
})
};
這將返回Promise
是由.then
調用返回。這個承諾將解決到resultOfModification
,因爲這是你回報的價格。
這樣,你可以使用getSlices
這樣:
service.getSlices().then(function(modifiedData) {
});
承諾可以鏈接起來:
(new Promise(function(resolve, reject){
setTimeout(function() {
resolve("some");
},200);
}))
.then(function(data) {
return data+' data';
})
.then(function(data) {
//here a Promise is return which will resovle later (cause of the timeout)
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(data+' !!!!!!');
},200);
});
})
.then(function(data) {
//this will have 'some data !!!!!!'
console.log(data);
});
這將是,如果你會寫這樣的說法相同:
var promiseA = new Promise(function(resolve, reject){
setTimeout(function() {
resolve("some");
},200);
});
var promiseB = promiseA.then(function(data) {
return data+' data';
})
var promiseC = promiseB.then(function(data) {
//here a Promise is return which will resovle later (cause of the timeout)
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(data+' !!!!!!');
},200);
});
});
var promiseD = promiseC.then(function(data) {
//this will have 'some data !!!!!!'
console.log(data);
});
您無法返回它在那個地方作爲實際值,因爲'Restangular'是異步的('getSlices'在調用'then'回調之前被留下)。這就是爲什麼使用'Promise'的原因。所以_correct_方法將返回Promise,並執行:'service.getSlices()。then(function(resultOfModification){});'? – 2014-09-04 19:31:54
我已經成像了,這可能是不可行的,雖然我希望可能有某種方式打破這種異步。我將如何使'getSlices()'返回一個包含我的'resultOfModification'的承諾? – omilke 2014-09-04 19:36:20