如何重复“请求”,直到成功? 的NodeJS

我在StackOverflow中检查了一些线程,但没有为我工作。 我有这个请求调用,我需要它尝试发送请求,直到它成功(但如果失败,它必须等待至less3秒):

sortingKeywords.sortVerifiedPhrase = function(phrase) { var URL = "an API URL"+phrase; //<== Obviously that in my program it has an actual API URL request(URL, function(error, response, body) { if(!error && response.statusCode == 200) { var keyword = JSON.parse(body); if(sortingKeywords.isKeyMeetRequirements(keyword)){ //Check if the data is up to a certain criteria sortingKeywords.addKeyToKeywordsCollection(keyword); //Adding to the DB } else { console.log("doesn't meet rquirement"); } } else { console.log(phrase); console.log("Error: "+ error); } }); }; 

这是一个奇怪的部分,如果我从浏览器中调用同一个短语,它几乎没有错误(它通常指出:限制时间已到)。

感谢你的帮助。 提前致谢。

这是我为这个请求写的一个工作程序。 它通过函数发送请求,如果请求失败,则返回error处理程序并再次调用该函数。

如果函数成功,程序返回一个promise并退出执行。

注意:如果你input一个无效的URL,程序马上退出,这是与request模块有关的事情,我喜欢说实话。 它让你知道你有一个无效的url。 所以你必须在url中包含https://http://

 var request = require('request'); var myReq; //our request function function sendTheReq(){ myReq = request.get({ url: 'http://www.google.com/', json: true }, (err, res, data) => { if (err) { console.log('Error:', err) } else if (res.statusCode !== 200) { console.log('Status:', res.statusCode) } else { // data is already parsed as JSON: //console.log(data); } }) } sendTheReq(); //promise function function resolveWhenDone(x) { return new Promise(resolve => { myReq.on('end', function(){ resolve(x) }) myReq.on('error', function(err){ console.log('there was an error: ---Trying again'); sendTheReq(); //sending the request again f1(); //starting the promise again }) }); } //success handler async function f1() { var x = await resolveWhenDone(100); if(x == 100){ console.log("request has been completed"); //handle other stuff } } f1(); 

在错误运行此代码

setTimeout(function(){}, 3000);

看到这个https://www.w3schools.com/jsref/met_win_settimeout.asp

你也可以做这样的代码

var func1 = function(){}; setTimeout(func1, 3000);