问题描述
这是在node.js中的典型情况:
This is a typical situation in node.js:
asyncFunction(arguments, callback);
在 asynFunction
完成后,回调
被调用。我用这种模式看到的一个问题是,如果 asyncFunction
的从不的结束(和 asynFunction
没有内置超时系统),那么回调
将永远不会被调用。更糟的是,它似乎回调
没有确定 asynFunction
将永远不会返回的路。
When asynFunction
completes, callback
gets called. A problem I see with this pattern is that, if asyncFunction
never completes (and asynFunction
doesn't have a built-in time-out system) then callback
will never be called. Worse, it seems that callback
has no way of determining that asynFunction
will never return.
我想实现一个超时,即如果回调
未在1秒钟之内被称为由 asyncFunction
,那么回调
自动被调用,并假设 asynFunction
已经出错了。什么是这样做的标准方式?
I want to implement a "timeout" whereby if callback
has not been called by asyncFunction
within 1 second, then callback
automatically gets called with the assumption that asynFunction
has errored out. What is the standard way of doing this?
推荐答案
我不熟悉做任何库,但它不是很难线了自己。
I'm not familiar with any libraries that do this, but it's not hard to wire up yourself.
// Setup the timeout handler
var timeoutProtect = setTimeout(function() {
// Clear the local timer variable, indicating the timeout has been triggered.
timeoutProtect = null;
// Execute the callback with an error argument.
callback({error:'async timed out'});
}, 5000);
// Call the async function
asyncFunction(arguments, function() {
// Proceed only if the timeout handler has not yet fired.
if (timeoutProtect) {
// Clear the scheduled timeout handler
clearTimeout(timeoutProtect);
// Run the real callback.
callback();
}
});
这篇关于实施node.js的回调超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!