问题
OK so in the below example I request something from a server. If a response comes back I parse the JSON and add the data to my mongodb.
However if NO response comes back, then no event fires evidently. How would I add a timeout to this so that if no response is received, then I can cancel the request without any errors being thrown, and call a function? (I'm going to make it call a function that emails me.)
Thanks!
var req = https.request(options, function(res) {
res.on('data', function(d) {
if(d) buffer += d;
});
res.on('end', function(){
var validResponse = true;
var object;
try {
object = JSON.parse(buffer);
} catch (err) {
console.log('response: '+ buffer);
console.log('error in response: ' + err);
validResponse = false;
}
if(validResponse) {
db.stuff.update(
{stuff: "MyStuff"},
{stuff: "MyStuff", foo: object.bar},
{upsert: true},
function() {
var time2 = new Date();
console.log('db successfully updated db at '+time2.toTimeString());
}
);
}
});
});
回答1:
You can use request.setTimeout(timeout, [callback]) api.
req.setTimeout(5000, function() {
console.log('timed out');
req.abort();
});
来源:https://stackoverflow.com/questions/21872833/in-node-js-if-no-response-is-received-from-an-http-request-how-do-you-know