lundi 2 mars 2015

Calling async functions recursively

I need to have an async method eg. getWeather called forever with a small delay between the success of previous call and beginning of the next call. I have used a recursive function for the purpose. I am concerned if this can cause a performance hit. Are there any better ways to do this?



var request = require('request');
var Promise = require('bluebird');

var delayTwoSecs = function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve();
}, 2000);
});
};

var getWeather = function() {
return new Promise(function(resolve, reject) {
request({
method: 'GET',
uri: 'http://ift.tt/1fT1uDr'
}, function(error, response, body) {
if (error) {
reject(error);
} else {
resolve(body)
}
});
});
};

var loopFetching = function() {
getWeather()
.then(function(response) {
console.log(response);
return delayTwoSecs();
}).then(function(response) {
loopFetching();
});
};

loopFetching();

Aucun commentaire:

Enregistrer un commentaire