I have such function:
function getStatusCode(site){
var options = {
host: "127.0.0.1",
port: 8000,
path: site,
headers: {
Host: site
}
};
var status;
http.get(options, function(response) {
status=response.statusCode;
});
return status;
}
How to return status only when http.get finish work or return null if timeout(e.g. 10 seconds)?
The whole idea behind node.js is its asynchronous nature. What you are trying to do is to violate the design pattern that is at the very root of it by trying to make it synchronous.
Due to the asynchronous nature of the
getmethod you cannot do this. You can manipulate the status code only inside the callback function. So yourgetStatusCodedoesn’t need to return anything. You could make it take an additional parameter which will represent a callback invoked once the results are available:and then: