gpt4 book ai didi

javascript - For Each 循环中的 Promise 在 AngularJS 中不起作用

转载 作者:行者123 更新时间:2023-12-01 03:50:48 25 4
gpt4 key购买 nike

传入的“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"
]
]

最佳答案

这说明 Promise 只能以一个值解析。对同一个延迟对象进一步调用 resolve 都不会产生任何效果。这就是为什么你一遍又一遍地获取第一个对象作为值。这是 Promises/A+ specifications, point 2.1.2 所要求的行为(强调我的):

2.1.2 When fulfilled, a promise:

     2.1.2.1 must not transition to any other state.

     2.1.2.2 must have a value, which must not change.

当然,如果允许更改 Promise 的值,那么您仍然不会得到所需的结果,因为结果会重复 < em>最后对象值。

要解决此问题,请在循环内创建一个新的延迟对象,以便始终解决新的 Promise:

移动这个:

var deferred = $q.defer();

进入forEach回调:

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

关于javascript - For Each 循环中的 Promise 在 AngularJS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43224525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com