我有这个例子:
var lastTime = '';
$scope.loadEvents = function () {
var items = listEvents();
items.then(function (data) {
lastTime = data;
});
};
$scope.openModal = function (data) {
//i want to use lastTime here;
};
当我点击按钮时,我正在调用openModal()
,并且我想确保返回data
。
所以我认为我必须从 loadEvents()
函数返回一个 promise
有什么想法吗?
最佳答案
如果您想确保从异步操作中获取数据,最好的处理方法是从源返回 promise (尽管将其链接起来)并在 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;
});
};
为了避免在服务器尚未返回响应时进行多个同时调用,您可以返回之前创建的相同 promise 。
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;
};
但是这种缓存 promise 逻辑理想情况下您应该尝试在服务中而不是在 Controller 上处理它......
关于javascript - 在 AngularJS 中返回一个 Promise 的好方法,怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25234095/