Is there a way in JavaScript to send an HTTP request to an HTTP server and wait until the server responds with a reply? I want my program to wait until the server replies and not to execute any other command that is after this request. If the HTTP server is down I want the HTTP request to be repeated after a timeout until the server replies, and then the execution of the program can continue normally.
Any ideas?
Thank you in advance, Thanasis
Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait .
I would use async/await. If you run your whole main program in an async function that you call immediately, you can put await before any function that returns a Promise .
There is a 3rd parameter to XmlHttpRequest
's open()
, which aims to indicate that you want the request to by asynchronous (and so handle the response through an onreadystatechange
handler).
So if you want it to be synchronous (i.e. wait for the answer), just specify false for this 3rd argument. You may also want to set a limited timeout
property for your request in this case, as it would block the page until reception.
Here is an all-in-one sample function for both sync and async:
function httpRequest(address, reqType, asyncProc) { var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); if (asyncProc) { req.onreadystatechange = function() { if (this.readyState == 4) { asyncProc(this); } }; } else { req.timeout = 4000; // Reduce default 2mn-like timeout to 4 s if synchronous } req.open(reqType, address, !(!asyncProc)); req.send(); return req; }
which you could call this way:
var req = httpRequest("http://example.com/aPageToTestForExistence.html", "HEAD"); // In this example you don't want to GET the full page contents alert(req.status == 200 ? "found!" : "failed"); // We didn't provided an async proc so this will be executed after request completion only
You can perform a synchronous request. jQuery example:
$(function() { $.ajax({ async: false, // other parameters }); });
You should take a look at jQuery's AJAX API. I highly recommend using a framework like jQuery for this stuff. Manually doing cross-browser ajax is a real pain!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With