实现node.js回调的超时

Ran*_*lue 30 javascript asynchronous node.js

这是node.js中的典型情况:

asyncFunction(arguments, callback);
Run Code Online (Sandbox Code Playgroud)

asynFunction完成后,callback被调用.我看到这个模式的一个问题是,如果asyncFunction 永远不会完成(并且asynFunction没有内置的超时系统),那么callback永远不会被调用.更糟糕的是,似乎callback没有办法确定asynFunction永远不会回来.

我想实现一个"超时",如果在1秒内callback没有被调用asyncFunction,那么会callback自动调用带有asynFunction错误的假设.这样做的标准方法是什么?

Ale*_*yne 24

我不熟悉任何执行此操作的库,但是自己连接起来并不困难.

// 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();
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 没有竞争条件,因为JS运行单个线程队列 (4认同)

小智 7

您可能需要提出自己的解决方案.喜欢

function callBackWithATimeout (callback, timeout) {
  var run, timer;
  run = function () {
    if (timer) {
      clearTimeout(timer);
      timer = null;
      callback.apply(this, arguments);
    }
  };
  timer = setTimeout(run, timeout, "timeout");
  return run;
}
Run Code Online (Sandbox Code Playgroud)

然后

asyncFunction(arguments, callBackWithATimeout(callback, 2000));
Run Code Online (Sandbox Code Playgroud)