我有两个API请求,每个请求都异步获取数据,这些数据必须在运行另一个函数之前可用。
我一直在研究Promise,但不知道如何在这个场景中实现它们。
使用此代码,在不使用setTimeout方法的情况下,如何在运行依赖函数之前等待从这些函数返回的数据?
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)发布于 2018-03-21 20:01:41
我假设JA是$的别名
您需要使用promise链:
JA.get('api/' + companyId + '/Invoicing')
.done(function(result) {
...processing of result
//this resurns the promise so the second done will run
return JA.get('api/' + companyId + '/Expenses');
})
.done(function(result){
..processing of second result
});没有设置超时。
发布于 2018-03-21 19:44:26
您可以使用Promise.all()等待一组promises,并且只有在完成了.then()中的某些操作之后才可以使用它
有关更多信息,请参阅MDN文档。
发布于 2018-03-21 19:48:13
虽然promises可能是更好的解决方案,但你可以通过检查数据来做到这一点:
var invoices = null;
var expenses = null;
JA.get('api/' + companyId + '/Invoicing', function(err, data) {
...
if (data) {
invoices = data.Items;
// Call calc here
calcRevenue();
}
}
})
JA.get('api/' + companyId + '/Expenses', function(err, data) {
...
if (data) {
expenses = data.Items;
// And here
calcRevenue();
}
}
})
function calcRevenue() {
if (invoices == null || expenses == null) return;
... else both have loaded, ready to do the calc
}如果需要重新调用任一ajax调用,请先清除invoices/expenses变量。
https://stackoverflow.com/questions/49405439
复制相似问题