Node.js killing an async call
Is there any way in Node.js to kill an async operation and preventing it from completing (calling callbacks, or resolving promise) ?
To be more specific, let's say I did an http.get()
call. It is an async operation that eventually will call the callback passed, or fire an error event. But it takes too long and the logic in my code could say "hey, I have been waiting for so long, I don't want to wait any longer!" and do something else instead. The problem is, the callback will eventually be called, and that might mess up stuff! So yeah, is there a way to stop that callback from being executed? My idea was:
var notWaitingAnyMore = false;
http.get({}, function(res) {
if(notWaitingAnyMore) { // do stuff! }
});
//do some other stuff
//now fed up with waiting:
notWaitingAnyMore = true;
But this doesn't seem like a nice solution to me...
Your best bet is probably to use promises. For example, if you are using bluebird
, this problem is very easily solved:
new Promise(function(resolve, reject) {
http.get({}, resolve);
}).timeout(500) // timeout length in ms
.then(function(res) {
// do stuff!
}).catch(Promise.TimeoutError, function(err) {
// do you need to do something after it times out?
})
//do some other stuff
你超级密切
function outerMethod(input, callback){
var notWaitingAnyMore = false;
var maxTimeout = 1000*60; // 1min
http.get({}, function(res) {
if(!notWaitingAnyMore) {
// do stuff!
notWaitingAnyMore = true;
callback(null, res);
} else {
return;
}
});
setTimeout(function(){
// We want to avoid calling back a second time if the http callback ran first:
if(!notWaitingAnyMore) {
notWaitingAnyMore = true;
callback('timeout');
} else {
return
}
}, maxTimeout)
};
链接地址: http://www.djcxy.com/p/52702.html
下一篇: Node.js杀死一个异步调用