我正在编写一个仅限服务器的应用程序,它从API获取数据,检查是否有新内容,并向所有连接发出更新。唯一的限制是必须按创建顺序(按时间顺序或通过pk)发出更新,并且请求可能会受到先前请求的响应的影响。
我面临的问题是,当请求需要很长时间,另一个请求可能会超过它,并开始“轮流”发送更新。
最好的方法是什么?理想情况下,我希望这个流程:
request -> response -> emit ... request -> response -> emit ...
注意:如果请求失败或超时,我想至少重试X次。
答案 0 :(得分:0)
你可以使用回调
function check(){
//request to the api
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
// here you can emit your events
// do your events
// after done your events, you can call check again
check()
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}
check()
答案 1 :(得分:0)
有两种快速解决方法。
您可以使用回调并递归使用您的函数
var myCall = function(){
var request = new XMLHttpRequest();
request.open(<request_method>, <request_url>, true);
request.send(null);
if (request.status === 200) {
//put your emit function here
myCall();
}
}
myCall();
您可以同步拨打电话。如果您正在进行连续通话,我不建议这样做
var myCall = function(){
var request = new XMLHttpRequest();
request.open(<request_method>, <request_url>, false); //false makes it synchronous
request.send(null);
if (request.status === 200) {
//put your emit function here
}
}
myCall();
myCall();
myCall();
myCall();
.
.
.
as many times as u want