小编典典

为node.js回调实现超时

node.js

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

asyncFunction(arguments, callback);

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

我想实现一个“超时”,如果callback没有asyncFunction在1秒钟之内调用它,那么将callback自动以asynFunction错误提示进行调用。这样做的标准方法是什么?


阅读 258

收藏
2020-07-07

共1个答案

小编典典

我不熟悉执行此操作的任何库,但连接起来并不难。

// 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();
  }
});
2020-07-07