![](/img/trans.png)
[英]How can I run an asynchronous function inside a loop and get a return value (Node.js/Javascript)
[英]How to set a time limit to run asynchronous function in node.js?
有一个异步函数fun(param, callback)
如下所示:
fun(param, function(err){
if(err) console.log(err);
doSomething();
});
如何设置运行此功能的时间限制?
例如,我将时间限制设置为等于10秒。
如果它在10秒内完成,则没有错误。
如果它超过10秒,则终止它并显示错误。
承诺是这种行为的理想选择,你可以拥有类似的东西:
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这样的东西,你可以找到更强大的工具,比如函数或整个模块的promisification和承诺超时。
http://bluebirdjs.com/docs/api/timeout.html
我认为这是首选方法。 希望这可以帮助
最简单的方法是在promise中捕获函数。
var Promise = require("bluebird");
var elt = new Promise((resolve, reject) => {
fun(param, (err) => {
if (err) reject(err);
doSomething();
resolve();
});
elt.timeout(1000).then(() => console.log('done'))
.catch(Promise.TimeoutError, (e) => console.log("timed out"))
我制作了一个模块'intelli-timer'
var timer = require('intelli-timer');
timer.countdown(10000, function(timerCallback){ // time limit is 10 second
do_something_async(err, function(){
timerCallback(); // timerCallback() after finish
});
}, function(err){
if(err) console.log(err); // err is null when the task is completed in time
else console.log('success');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.