有一个异步函数fun(param, callback)
是这样的:
fun(param, function(err){
if(err) console.log(err);
doSomething();
});
如何设置运行此功能的时间限制?
例如,我将时间限制设置为 10 秒。
如果在 10 秒内完成,则没有错误。
如果它运行超过 10 秒,则终止它并显示错误。
最佳答案
Promises 是这种行为的理想选择,您可以拥有类似的东西:
new Promise(function(resolve, reject){
asyncFn(param, function(err, result){
if(error){
return reject(error);
}
return resolve(result)
});
setTimeout(function(){reject('timeout')},10000)
}).then(doSomething);
这是使用基本的 ES6 Promise 实现。然而,如果你想包含像 bluebird 这样的东西,你可以找到更强大的工具,比如函数或整个模块的 promise 和 promise 超时。
http://bluebirdjs.com/docs/api/timeout.html
我认为这是首选方法。 希望这有帮助
关于javascript - 如何设置在 node.js 中运行异步函数的时间限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36587789/