Arrays $q.all使用angularjs中的循环创建动态承诺
我想做一个循环,这是我的第二个承诺,所以每次它通过我的循环时,一个新的承诺被创建:Arrays $q.all使用angularjs中的循环创建动态承诺,arrays,angularjs,angular-promise,Arrays,Angularjs,Angular Promise,我想做一个循环,这是我的第二个承诺,所以每次它通过我的循环时,一个新的承诺被创建: var promise1 = $http({ method: 'GET', url: "https://cubber.zendesk.com/api/v2/organizations/"+id+"/users.json", dataType: 'json', headers: {'Content-Type': 'application/json', 'Authoriza
var promise1 = $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/organizations/"+id+"/users.json",
dataType: 'json',
headers: {'Content-Type': 'application/json',
'Authorization': 'Bearer '+token}
});
var promise2 = promise1.then(function(data) {
console.log(data);
for(i = 0; i < data.data.users.length; i++){
console.log(data.data.users.length);
var userid = data.data.users[i].id;
console.log(userid);
return $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/users/"+userid+"/tickets/requested.json",
dataType: 'json',
headers: {'Content-Type': 'application/json',
'Authorization': 'Bearer '+token}
})
}
});
$q.all([promise1, promise2]).then(function(data){
console.log(data[0].data.users, data[1]);
});
在这段代码中,循环不起作用,因为promise2只返回一个结果
你能帮我吗?把你的代码想象成一系列你想触发的事件。忘记同步-忘记逐行透视图 在本例中,我们触发第一个http请求。然后,作为对请求的响应,我们发出一组userid http请求,并建立一个返回承诺的数组列表 然后使用$q.all,我们对所有这些承诺作出collectivley响应,并做一个控制台日志
var promise1 = $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/organizations/"+id+"/users.json",
dataType: 'json',
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer '+token}
});
promise1.then(function(data) {
var allQ = [];
var allData = [];
console.log(data);
for(i = 0; i < data.data.users.length; i++){
console.log(data.data.users.length);
var userid = data.data.users[i].id;
console.log(userid);
allQ.push( $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/users/"+userid+"/tickets/requested.json",
dataType: 'json',
headers: {'Content-Type': 'application/json',
'Authorization': 'Bearer '+token}
}).then( function(data){ allData.push( data)} ) );
}
$q.all(allQ).then(function(data){
//You will probably want to iterate allData
console.log( allData);
});
});
非常感谢您的回答,这是非常有帮助的,但是,我没有从promise1获得数据,这是合乎逻辑的,因为'allQ'在我的函数结果的参数中。哦,天哪。是的,返回的数据,很抱歉我错过了。让我更新一下。因为在我需要将来自每个承诺的所有数据包装到同一个数组中之后,这将不容易:p