传入的“types”参数格式为["hourAverage","hourMedian","dayAverage","dayMedian","weekAverage","weekMedian","monthAverage","monthMedian"]
来源:
$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"
]
]
答案 0 :(得分:2)
这表明承诺只能用一个值来解决。 resolve
对同一延迟对象的进一步调用将不起作用。这就是为什么你一遍又一遍地将第一个对象作为值。这是Promises/A+ specifications, point 2.1.2(强调我的)所需的行为:
2.1.2满足后,承诺:
2.1.2.1不得过渡到任何其他州。
2.1.2.2必须有一个值,不得更改。
当然,如果 允许更改承诺的值,那么你仍然不会得到所需的结果,因为结果会重复< em> last 对象值。
要解决此问题,请在循环中创建一个新的延迟对象,以便始终解决新的承诺:
移动它:
var deferred = $q.defer();
进入forEach
回调:
types.forEach(function(type){
var deferred = $q.defer();
// etc...