Ran*_*lue 30 javascript asynchronous node.js
这是node.js中的典型情况:
asyncFunction(arguments, callback);
当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();
  }
});
小智 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;
}
然后
asyncFunction(arguments, callBackWithATimeout(callback, 2000));
| 归档时间: | 
 | 
| 查看次数: | 16541 次 | 
| 最近记录: |