实施node.js的回调超时

实施node.js的回调超时

问题描述:

这是在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();
  }
});