0

我有这个例子:

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()所以我想我必须从函数中返回一个承诺

有任何想法吗?

4

1 回答 1

2

如果你想确保从异步操作中获取数据,最好的处理方法是从源返回承诺(尽管链接它)并在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;
};

但是这个缓存承诺逻辑你应该理想地尝试在服务中而不是在控制器上处理它......

于 2014-08-10T23:45:18.677 回答