我检查了 StackOverflow 中的几个线程,但对我没有任何作用。 我有这个请求调用,我需要它尝试发送请求直到成功(但如果失败,则必须等待至少 3 秒):
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 并退出执行。
注意:如果您输入无效的 url,程序会立即退出,这与 request
模块有关,老实说。它会让您知道您的网址无效。所以你必须在 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();
关于javascript - 如何重复 "request"直到成功? Node JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46106484/