目前我有一個函數可以從數據庫中返回前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
});
});
});
};
您可以簡單地返回的HTTP $值作爲承諾:$ http.get(),然後(函數(){$返回http.get(),則()。 }); –