你不能在那个地方作为实际值返回它,因为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