这是node.js中的典型情况:
asyncFunction(arguments, callback);
当 asynFunction
完成时,callback
被调用。我看到这种模式的一个问题是,如果 asyncFunction
never 完成(并且 asynFunction
没有内置的超时系统) 那么 callback
将永远不会被调用。更糟糕的是,callback
似乎无法确定 asynFunction
永远不会返回。
我想实现一个“超时”,如果 callback
在 1 秒内没有被 asyncFunction
调用,那么 callback
会自动被调用假设 asynFunction
已出错。这样做的标准方法是什么?
最佳答案
我不熟悉任何这样做的库,但自己连接起来并不难。
// 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();
}
});
关于javascript - 为 node.js 回调实现超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8377777/