I wrote a JavaScript function named fetchAandB that accepts a callback as a parameter. This function first makes an ajax call to retrieve the value 'a'. Once it gets the value, it invokes the callback function with 'a' passed as an argument. The callback then retrieves the value 'b' and logs both 'a' and 'b' in the console. As a result, I see
{"key":"a"} {"key":"b"}
displayed in the console.
Initially, I assumed that the two ajax calls would be executed simultaneously or asynchronously. However, it seems that they are running synchronously, one after the other.
Below, you can find the JavaScript code for the ajax requests:
index.html:
<script>
function fetchAandB(callback){
const xhr = new XMLHttpRequest();
xhr.open('GET', './ajax-a.php', true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
callback(xhr.responseText)
}
}
xhr.send();
}
function callback(resultA){
const xhr = new XMLHttpRequest();
xhr.open('GET', './ajax-b.php', true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
const resultB = xhr.responseText;
console.log(resultA, resultB);
}
}
xhr.send();
}
fetchAandB(callback);
</script>
ajax-a.php:
<?php
sleep(5);
$response = [
"key" => "a",
];
echo json_encode($response);
The code for ajax-b.php is identical to ajax-a.php except that the value of $response.key is 'b' instead of 'a'.
I expected the above code to trigger ajax calls simultaneously for 'a' and 'b'. However, when the PHP script sleeps for 5 seconds in both ajax-a.php and ajax-b.php, it takes a total of 10 seconds for the console.log output to appear. If only one of the scripts sleeps for 5 seconds, then it takes 5 seconds for the output to display.
Is there a way to utilize callbacks to combine the results of ajax calls like this while ensuring that the individual calls execute simultaneously or asynchronously? Or is this not achievable using callbacks?