I have two API requests, each of which asynchronously fetch data that must be available before running another function.
I've been looking into Promises, but have no idea how I'd implement them into this scenario.
Using this code, how can I await returned data from these before running my dependent function without using a setTimeout method?:
var invoices = null;
var expenses = null
var invoicesTotal = 0;
var expensesTotal = 0;
JA.get('api/' + companyId + '/Invoicing', function(err, data) {
if (err) {
console.error('Error getting Invoicing data:', err);
} else {
if (data) {
invoices = data.Items;
console.log('Successfully retrieved Invoicing data:', data.Items);
} else {
console.log('No invoicing data found');
}
}
})
JA.get('api/' + companyId + '/Expenses', function(err, data) {
if (err) {
console.error('Error retrieving expenses data:', err);
} else {
if (data) {
expenses = data.Items;
} else {
console.log('No expenses data found');
}
}
})
/* CALCULATE TOTAL REVENUE */
function calcRevenue() {
....
}
setTimeout(function() {
calcRevenue();
}, 1000)