My application makes GET requests to my node/express server. To check for changes in my server code, I have added a setTimeout function. My promise function in my client side code works fine for a couple of minutes but eventually stops working and throws an error if it takes too long to get something in return from the server. Is there a way to keep the promise function running until it gets data back from the server instead of throwing an error immediately? Basically, I want the timeout to keep running in the server and check for changes and I want the getMessageData()
promise function to keep running for as long as it can.
This is my factory code in my angular app that GETs data from my remote server built in nodeJS/Express:
app.factory('getMessageData', ['$q', '$http', function($q, $http) {
var last_updated_time = 0;
return function getData() {
var deferred = $q.defer();
console.log("Time stamp is: "+last_updated_time);
var req = $http({
url: 'https://20161128t161542-dot-jarvis-hd-live-2.appspot-preview.com/read-message',
method: 'GET',
cache: false,
params: {last_updated: last_updated_time}
});
req.success(function(object) {
last_updated_time = object.time_stamp;
deferred.resolve(object);
});
req.error(function(err) {
console.log("there was an error: "+err);
deferred.reject(err);
});
return deferred.promise;
}
}]);
This is my directive code that calls and initiates the factory code to make the request:
app.directive('message', ['getMessageData', function(getMessageData) {
return {
restrict: 'E',
templateUrl: 'scripts/directives/message.html',
link: function (scope) {
function getMessage(){
getMessageData().then(function(message_data){
var message = message_data.data;
scope.message = message;
getMessage();
}, function(err){
console.log("Error: " + err);
});
}
getMessage();
}
}
}]);
This is my server code for making a GET request to the /read-message url:
app.get('/read-message', function(req,res){
var last_updated_time = req.query.last_updated;
function checkMessage() {
if(!last_updated_time || last_updated_time < new_time){
updateMessage();
}
else {
setTimeout(function(){
checkMessage();
}, 1000 * 10); //10 seconds
}
}
function updateMessage() {
var output = {
success: 1,
data: message,
time_stamp: new_time
};
return res.json(output);
}
checkMessage();
});