I have to call two APIs to get some values. Then I am able to present the results to a user. I have achieved that by making sequential calls through callbacks:
function firstApi() {
callFirstApi(function(firstValue) {
secondApi(firstValue);
});
}
function secondApi(firstValue) {
callSecondApi(function(secondValue) {
presentResults(firstValue, secondValue);
});
}
function presentResults(firstValue, secondValue) {
// do something...
}
The problem that bothers me is that API calls could be asynchronous. I would like to know if there are any problems with such solution:
var firstValue = null;
var secondValue = null;
function apiResult(value) {
if (firstValue === null) {
firstValue = value;
return;
}
secondValue = value;
presentResults();
}
function presentResults() {
// do something...
}
firstApiCall(apiResult);
secondApiCall(apiResult);
JavaScript is single-threaded but I am still not sure where the context switch might occur. In other words, if there is a possibility that function call would be interrupted in the middle of execution when the asynchronous call was finished (so that for instance firstValue null check would pass for both execution paths and the second value would never be set).