Hey I'm using promise to fetch 2 different API calls, that both return files with similar/matching data.
I'm trying to use one of the API calls to display a couple of numbers (balance of 2 wallets), which worked fine when there was only one API call, I was doing it like this:
const rewardWallet = data.result[0];
const rewardBalance = rewardWallet.balance;
So, data.result[0] was selecting result, and then the first array (0) and then the data from 'balance'. But now that there are 2 API calls, 'result' is under '0' and I can't figure out how to select the top level.
I added the second API call like this:
Promise.all([
fetch('https://api.bscscan.com/api?module=account&action=balancemulti&address=0xa3968Fba9D45D52b6b978f575934364ac2d5774c,0x121F0a592a25A52E8834C87005CbF4db000010Af&tag=latest&apikey=key'),
fetch('https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0x7b50c95f065dc48a0ecf8e5f992bf9bb9f4299c5&address=0x121F0a592a25A52E8834C87005CbF4db000010Af&tag=latest&apikey=key')
]).then(function (responses) {
return Promise.all(responses.map(function (response) {
return response.json();
}));
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.log(error);
});
Appreciate any help.
You can use Promise.all to ensure request are fired off and then work with the response after all promises have resolved. See below, I've added some mock functions that mock the API calls that will just return an object with an amount.
const fetchWalletOne = () => {
return new Promise((resolve) => {
resolve({ amount: 1 });
});
};
const fetchWalletTwo = () => {
return new Promise((resolve) => {
resolve({ amount: 5 });
});
};
async function getData() {
const [walletOne, walletTwo] = await Promise.all([
fetchWalletOne(),
fetchWalletTwo()
]);
console.log(walletOne, walletTwo);
console.log(walletOne.amount + walletTwo.amount);
}
getData();