如果你想确保从异步操作中获取数据,最好的处理方法是从源返回承诺(尽管链接它)并在OpenModal
. 这将确保无论何时您单击模式,数据将始终返回并且不存在同步问题。
$scope.loadEvents = function () {
var items = listEvents();
return items.then(function (data) { //Make the loadEvents return a promise
return data; //return the data after any mapping or anything you may want to do
});
};
$scope.openModal = function (data) {
$scope.loadEvents().then(function(data){ //
lastTime = data;
});
};
为了避免在响应尚未从服务器返回时同时调用多个,您可以返回之前创建的相同承诺。
var _cachedPromise;
$scope.loadEvents = function () {
var items = listEvents();
//Actually you could chain all these together but for clarity steps have been broken down.
if(_cachedPromise) return _cachedPromise;
_cachedPromise = items.then(function (data) { //Make the loadEvents return a promise
return data; //return the data after any mapping or anything you may want to do
});
//Cleanup promise to make fresh calls.
_cachedPromise.finally(function(){
_cachedPromise = null;
});
return _cachedPromise;
};
但是这个缓存承诺逻辑你应该理想地尝试在服务中而不是在控制器上处理它......