Angular-等待异步任务完成
问题描述:
目前我有一个函数可以从数据库中返回前5名客户。但是,返回的对象只包含{userId,visitCount}。为了检索用户名,我需要进行另一个API调用以基于userId获取用户的配置文件。最终对象($ scope.topFiveCustomer)将包含以下信息{userId,visitCount,name}。
问题:
我检索到的用户名后,当我使用的console.log打印$ scope.topFiveCustomers [0],该对象只包含{用户id,visitCount}。我想知道是否有任何方法可以等到检索名称(以下代码)完成后再执行其他任何操作?
_.each($scope.topFiveCustomers, function(customer) {
CustomerService.getCustomer(customer.uuid)
.then(function(response) {
customer['name'] = response.data.name;
})
});
当前代码:
$scope.getTopFive = function() {
DashboardService.getCustomerList($scope.topCustomerTime.value)
.then(function(customerList) {
$scope.topFiveCustomers = _.sortBy(customerList, 'visitCount').reverse().slice(0,5);
_.each($scope.topFiveCustomers, function(customer) {
CustomerService.getCustomer(customer.uuid)
.then(function(response) {
customer['name'] = response.data.name;
})
});
console.log($scope.topFiveCustomers);
//name: test
//uuid: 1234
//visitCount: 5
console.log($scope.topFiveCustomers[0]);
//uuid: 1234
//visitCount: 5
});
};
我试图用$ Q来解决这个问题:
function getCustomerName(){
var deferred = $q.defer();
_.each($scope.topFiveCustomers, function(customer) {
CustomerService.getCustomer(customer.uuid)
.then(function(response) {
customer['name'] = response.data.name;
})
});
deferred.resolve();
return deferred.promise;
}
$scope.getTopFive = function() {
DashboardService.getCustomerList($scope.topCustomerTime.value)
.then(function(customerList) {
$scope.topFiveCustomers = _.sortBy(customerList, 'visitCount').reverse().slice(0,5);
getCustomerName()
.then(function() {
new Chartist.Bar('#topCustomer', {
labels: [$scope.topFiveCustomers[0].uuid],
series: [$scope.topFiveCustomers[0].visitCount]
}, {
distributeSeries: true,
reverseData: true,
horizontalBars: true,
width: 250,
height: 250
});
});
});
};
答
你必须采取$q.all
功能的用户将等到所有五个客户数据被检索。 。
代码
function getCustomerName() {
var promises = [];
_.each($scope.topFiveCustomers, function(customer) {
//creating a promise array
promises.push(CustomerService.getCustomer(customer.uuid)
.then(function(response) {
customer['name'] = response.data.name;
}))
});
return $q.all(promises); //returning combined 5 promises array.
};
$scope.getTopFive = function() {
DashboardService.getCustomerList($scope.topCustomerTime.value)
.then(function(customerList) {
$scope.topFiveCustomers = _.sortBy(customerList, 'visitCount').reverse().slice(0, 5);
getCustomerName() //will wait till all promises get resolved.
.then(function(response) {
angular.forEach($scope.topFiveCustomers, function(customer) {
new Chartist.Bar('#topCustomer', {
labels: [customer.uuid],
series: [customer.visitCount]
}, {
distributeSeries: true,
reverseData: true,
horizontalBars: true,
width: 250,
height: 250
});
});
});
});
};
+0
感谢您的解决方案! – SL07
您可以简单地返回的HTTP $值作为承诺:$ http.get(),然后(函数(){$返回http.get(),则()。 }); –