2015-09-04 66 views
0

我有一個異步休息電話。在調用其他所有內容後,響應將在最後被檢索。在進入下一步之前,我需要回應。我計劃實施諾言。 我不知道如何執行諾言在我的情況。 我的代碼:

if($scope.savedDesc.length <= 0 && $scope.savedDesc != null && $scope.savedDesc != 'undefined') { 
    access.getDesc($scope.id, function(data){ 
     $scope.savedDesc = data; 
    }); 
} 

當$ scope.savedDesc設置,那麼只有我要進行下一步。

請建議。 在此先感謝。

+0

調用'callback'函數,即下一步線'$ scope.saveDesc'後。 –

+0

什麼是「訪問」? –

+0

@gauravbhavsar:我在$ scope.savedDesc = data之後有foreach,我將在這裏設置變量noteDesc。 noteDesc被傳遞給另一個其他呼叫。由於$ scope.savedDesc未設置,noteDesc以未定義形式傳遞。 – prashanth

回答

0

變化

if($scope.savedDesc.length <= 0 && $scope.savedDesc != null && $scope.savedDesc != 'undefined') { 
    access.getDesc($scope.id, function(data){ 
     $scope.savedDesc = data; 
    }); 
} 

// next step(s) here... 

if($scope.savedDesc.length <= 0 && $scope.savedDesc != null && $scope.savedDesc != 'undefined') { 
    access.getDesc($scope.id, function(data){ 
     $scope.savedDesc = data; 

     // next step(s) here... 
    }); 
} 
0

如果accessangular $resource,你可以做這樣的事情:

function nextStep(){ 
    //...do something with $scope.savedDesc... 
} 

$scope.savedDesc = access.getDesc($scope.id, nextStep); 

// or 

$scope.savedDesc = access.getDesc($scope.id); 
//... (do something else) 
$scope.savedDesc.$promise.then(nextStep); 
0

可以使用callback函數來實現一步一步執行。

if($scope.savedDesc.length <= 0 && $scope.savedDesc != null && $scope.savedDesc != 'undefined') 
{ 
    access.getDesc($scope.id, function(data){ 
     $scope.savedDesc = data; 
     noteDescCall($scope.savedDesc); // call foreach inside this function with $scope.saveDesc 
    }); 
} 

// your noteDescCall function which have `foreach` loop 

function noteDescCall(savedDesc){ 
    // implementation with savedDesc ... 
} 
0

OP詢問承諾。這裏有一個簡單的承諾鏈式例如:

MyAsyncRestCall() 
    .then(function(result1) { 
    // you can modify `result1` before returning it if you want 
    return result1; 
    }) 
    .then(function(result2) { 
    // `result2` is the data returned from the above `then` (e.g. `result1`) 
    // returning `result2` returns the value to the original caller 
    return result2; 
    }) 
    .catch(function(error) { 
    // handle errors here if you want to 
    return $q.reject({ message: JSON.stringify(error) }); 
    }); 

下面是關於承諾鏈接的好文章:http://www.syntaxsuccess.com/viewarticle/angular-promise-chaining-explained