更新时间:2021-12-11 22:16:38
您不能强迫 $ http.get()
进入同步。由于 $ http.get()
不可避免地异步的,你只能返回一个值,而不是值本身的承诺。
You can't force $http.get()
into synchronism. Since $http.get()
is unavoidably asynchronous, you can only return a promise of a value not the value itself.
因为你需要做到这一点时, $ http.get()
被调用时,还必须其他情况下返回一个承诺 - 当 vCardFromLS
成功从localStorage的retreived。这确保了对象返回到 $ scope.getVCard的任何呼叫()
有一个。然后()
方法,也就是说,它是一个承诺,无论 $ http.get()
被称为与否。
And because you need to do this when $http.get()
is called, you must also return a promise under the other condition - when vCardFromLS
is successfully retreived from localstorage. This ensures that the object returned to any call of $scope.getVCard()
has a .then()
method, ie it is a promise, regardless of whether $http.get()
was called or not.
所以,code应该是这样的:
So the code should be something like this :
$scope.getVCard = function(id) {
var vcardKey = vcardKeyPrefix + id;
var vCardFromLS = localStorageService.get(vCardKey);
var dfrd = $q.defer();
if(vCardFromLS) {
dfrd.resolve(localStorageService.get(vCardKey));
}
else {
$http.get(app.common.vcardUrl(id)).success(function(data) {
localStorageService.add(vCardKey, data);//.add() rather than .set() ?
dfrd.resolve(data);
}).error(function(error) {
F1.common.error(data, function() {
dfrd.reject('$http.get(app.common.vcardUrl(id)) failed');
});
});
}
return dfrd.promise;
};
现在,你需要确保对 $ scope.getVCard响应()
是适当的处理,例如:
Now you need to ensure that the response to $scope.getVCard()
is handled appropriately, eg :
$scope.getVCard(id).then(function(data) {
//success - do whatever is required with data
}, function(reason) {
//failure - log and/or display `reason` as an error message
})
编辑:
我的......您必须同时返回其他条件下的诺言......是言过其实。
My "... you must also return a promise under the other condition ..." is an overstatement.
我应该说,......你的可以,使事情变得简单,其他情况下返回一个承诺......
I should have said, "... you can, to make things simple, return a promise under the other condition ...".
另一种可能性是,这取决于是否返回一个承诺或其他类型的对象/值的分支。然而,这是混乱的,通常会导致code一些重复。
Another possibility is to branch depending on whether a Promise or another type of object/value was returned. However, this is messy and will typically lead to some duplication of code.