我是 Javascript 和 AngularJS 的新手,这个让我摸不着头脑:/
先决条件
- 从后端提供我的数据的 REST 服务
- AngularJS 1.2.21 和 Restangular 1.4.0
- 一个 AngularJS Controller ,它将向服务请求所提供的增强版本
我有什么
这是有问题的方法:
service.getSlices = function() {
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();
})
//I want the resultOfModification to be returned here
};
问题
基本上我想在 getSlices()
中等待,直到 promise 得到解决,以便仅在实际计算时返回我的 resultOfModification
。
其他场景
我还可以想象从 getSlices()
返回一个 promise ,然后它会提供 resultOfModification
。但是,我担心我对此了解不够和/或同时感到非常沮丧/疲倦。
欢迎回答和任何建议,尤其是指向好的阅读 Material 的指针。谢谢
最佳答案
你不能在那个地方将它作为实际值返回,因为 Restangular
是异步的(函数 getSlices
留在你传递给 的回调之前
被调用)。这就是使用 Promise
的原因。
即使可以使 Restangular
同步,您也不应该这样做,因为这会在请求数据之前阻塞浏览器,这将是糟糕的用户体验。
您应该尝试了解 Promise
,因为它们的设计看起来像同步代码,但行为却是异步的。
您需要在代码中更改的是在 Restangular.all
之前添加一个 return
:
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();
})
};
这将返回 .then
调用返回的 Promise
。此 Promise 将解析为 resultOfModification
,因为这是您从回调中返回的值。
这样你就可以这样使用 getSlices
:
service.getSlices().then(function(modifiedData) {
});
Promise 可以被链接起来:
(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);
});
关于javascript - Restangular:WAITING promise 的解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25673598/