service.php
service.php
is a
PHP script that takes a POST or GET parameter named
sleepSeconds
and then sleeps the indicated number of seconds. When it wakes up again, it returns a string to the originator of the request.
<?php
header('text/plain');
$sleepSeconds = $_REQUEST['sleepSeconds'];
sleep($sleepSeconds);
print("I just woke up after <b>$sleepSeconds seconds</b>.");
?>
main.html
main.html
is a
HTML document that makes three
fetch()
requests to
service.php
: the first requesting to sleep 3 seconds, the second to sleep 1 second, the third to sleep 2 seconds.
When the
fetch()
request returns, the returned string is written into a prepared
<div>
element.
A log keeps track when the requests were made. It can be seen that the entries into the log are written within less than a fraction of a second, thus prooving that the fetch requests are made in parallel (or asynchronously).
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<title>Asynchronous fetch</title>
</head>
<body>
<div id='s3'>Wait for request completion…</div>
<div id='s1'>Wait for request completion…</div>
<div id='s2'>Wait for request completion…</div>
<p>
<div id='log'></div>
<script>
function makeRequest(s) {
document.getElementById('log').innerHTML += new Date().toJSON() + ': Making request s=' + s + '<br>';
window.fetch('/service.php',
{
method : 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
'Accept' : 'text/plain'
},
body : new URLSearchParams({
'sleepSeconds': s
})
}).then(r => {
if (r.status !== 200) {
alert(r.status);
return;
}
r.text().then(txt => {
// document.getElementById('s' + s).innerText = txt;
document.getElementById('s' + s).innerHTML = txt;
});
}).catch(e => {
alert('Request produced an error: ' + e);
});
}
makeRequest(3);
makeRequest(1);
makeRequest(2);
</script>
</body>
</html>