Reputation: 1261
Here I have a simple Angular app with two services, one getting the balance of a Dogecoin public address, the second getting the price of Dogecoin in Btc, from two different source.
Services:
angular.module('AppName', ['ngResource'])
.factory('DogeBalance', ['$resource', function ($resource) {
return $resource("https://dogechain.info/api/v1/address/balance/:address");
}])
.factory('DogePrice', ['$resource', function ($resource) {
return $resource("https://chain.so/api/v2/get_info/DOGE");
}])
and the controller:
.controller('TwoController', function($scope, DogeBalance, DogePrice){
$scope.wallets = [
{ id: 0, type: 'doge', address: 'DT2rmMrutwzdZ8EXwzj4QFdcL6DtvGGkci'},
{ id: 1, type: 'doge', address: 'DMoonjyH1aHLZc1kksmikBUhjXromn1ZN4'}
];
var price = DogePrice.get();
$scope.totalBalance = parseFloat(0);
price.$promise.then(function(data) {
$scope.price = data.data.price;
//aggregate balance on all the addresses
for (i in $scope.wallets){
var balance = DogeBalance.get({address: $scope.wallets[i].address});
balance.$promise.then(function(data) {
$scope.totalBalance += parseFloat(data.balance);
$scope.totalValueBtc = $scope.totalBalance * $scope.price;
});
}
});
});
I need to calculate the aggregate value in BTC of the balances of all the dogecoin addresses from $scope.wallets
. I handled the promises from the two api calls in a nested way, as you can see in the controller code.
My question if there is a better way to do this data handling from multiple promises?
What if I have 5 promises to be resolved before data handling, each from different source? Do I need to place every one of them in the promise callback of the previous one?
Upvotes: 0
Views: 96
Reputation: 811
I would suggest putting your logic into a function that can be called from anywhere to sum up the value of all wallets in the array.
Start by making the balance a part of the wallet object.
$scope.wallets = [
{ id: 0, type: 'doge', address: 'DT2rmMrutwzdZ8EXwzj4QFdcL6DtvGGkci', balance: {}},
{ id: 1, type: 'doge', address: 'DMoonjyH1aHLZc1kksmikBUhjXromn1ZN4', balance: {}}
];
Then you can do
$scope.getBalance = function () {
var tempBalanace = 0;
angular.forEach($scope.wallets, function (value, key) {
tempBalance += value.balance * $scope.price;
});
$scope.totalBalance = tempBalance;
};
So now you can call $scope.getBalance() from all of your promises and the total balance will be updated accordingly. You may need to add some extra logic to handle a scenario where the balance or price is null (still awaiting a response), but whenever ANY record gets updated this will force an update of the overall balance with the last received values.
Upvotes: 1