2017-04-05 62 views
0

的 「類型」 工作的每個循環是在格式["hourAverage","hourMedian","dayAverage","dayMedian","weekAverage","weekMedian","monthAverage","monthMedian"]對於承諾不處於被傳遞參數angularjs

來源:

$scope.buildCharts = function(types){ 
    var deferred = $q.defer(); 
    var promises = []; 

    types.forEach(function(type){ 
       $scope.prepareData(type); 
       deferred.resolve([ 
       { 
        title: type, 
        curveType: 'function', 
        legend: { position: 'bottom' } 
       },type]); 
       promises.push(deferred.promise); 
    }); 
    return $q.all(promises); 
}; 

輸出:

[ 
    [ 
    { 
     "title": "hourAverage", 
     "curveType": "function", 
     "legend": { 
     "position": "bottom" 
     } 
    }, 
    "hourAverage" 
    ], 
    [ 
    { 
     "title": "hourAverage", 
     "curveType": "function", 
     "legend": { 
     "position": "bottom" 
     } 
    }, 
    "hourAverage" 
    ], 
    [ 
    { 
     "title": "hourAverage", 
     "curveType": "function", 
     "legend": { 
     "position": "bottom" 
     } 
    }, 
    "hourAverage" 
    ], 
    [ 
    { 
     "title": "hourAverage", 
     "curveType": "function", 
     "legend": { 
     "position": "bottom" 
     } 
    }, 
    "hourAverage" 
    ], 
    [ 
    { 
     "title": "hourAverage", 
     "curveType": "function", 
     "legend": { 
     "position": "bottom" 
     } 
    }, 
    "hourAverage" 
    ], 
    [ 
    { 
     "title": "hourAverage", 
     "curveType": "function", 
     "legend": { 
     "position": "bottom" 
     } 
    }, 
    "hourAverage" 
    ], 
    [ 
    { 
     "title": "hourAverage", 
     "curveType": "function", 
     "legend": { 
     "position": "bottom" 
     } 
    }, 
    "hourAverage" 
    ], 
    [ 
    { 
     "title": "hourAverage", 
     "curveType": "function", 
     "legend": { 
     "position": "bottom" 
     } 
    }, 
    "hourAverage" 
    ] 
] 

回答

2

這說明一個承諾只能用一個價值來解決。對同一個延遲對象的任何進一步的resolve調用都不起作用。這就是爲什麼你一次又一次地得到第一個對象的價值。這是由Promises/A+ specifications, point 2.1.2(重點煤礦)要求的行爲:

2.1.2完成時,一個承諾:

          2.1.2.1不能轉換爲任何其他國家。

          2.1.2.2必須有一個值,這不能改變

當然,如果被允許更改承諾的價值,那麼你還是不會有理想的結果,因爲那麼結果本來還有最後的重複對象值。

爲了解決這個問題,內循環創建一個新的Deferred對象,讓你始終解決新的承諾:

移動這樣的:

var deferred = $q.defer(); 

進入forEach回調:

types.forEach(function(type){ 
    var deferred = $q.defer(); 
    // etc...