javascript - 为 node.js 回调实现超时

标签 javascript node.js asynchronous

这是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/

相关文章:

javascript - JS中的每个对象都有一个toString()方法吗?

node.js - Angular2 ExpressJs - 文件上传到服务器

javascript - Bookshelf.js 或 Knex.js 中 2 个表的外部连接

javascript - 如何在 JavaScript 中组装异步请求的结果

python - 等待一个有 for 循环语法错误的函数

c# - 在任务完成之前等待不阻塞

javascript - ES6 中匿名函数的函数名称

javascript - 谷歌地图信息窗口滚动错误 : How to solve for all cases?

javascript - 指定父 div 不透明度但不影响子 HTML 元素

javascript - Chrome源代码中的ntp4代表什么?