我试图在setTimeout中使用回调递归调用nodejs函数。附加了代码段。它没有按预期工作。我错过了什么吗?
Model.xyz= function(cb){
//do something here and get the result.
if(result<10)
{
setTimeout(function(){
Model.xyz(cb);
},5000);
}
//once result is > 10 execute following code
}
答案 0 :(得分:1)
只需使用将永远调用您的方法的异步库
const async = require('async');
Model.xyz = cb => {
// do somethings
if(result < 10) return cb(null, true);
cb();
}
async.forever(cb => {
Model.xyz(repeat => {
// finish call and schedule next call
if(repeat === true) return setTimeout(cb, 5000);
cb('exit');
});
});