Javascript 递归调用异步函数
我需要一个异步方法,例如永远调用Javascript 递归调用异步函数,javascript,node.js,promise,bluebird,Javascript,Node.js,Promise,Bluebird,我需要一个异步方法,例如永远调用getWeather,在上一次调用成功和下一次调用开始之间有一个小的延迟。为此,我使用了一个递归函数。我担心这是否会导致性能下降。有没有更好的方法 var request = require('request'); var Promise = require('bluebird'); var delayTwoSecs = function() { return new Promise(function(resolve, reject) {
getWeather
,在上一次调用成功和下一次调用开始之间有一个小的延迟。为此,我使用了一个递归函数。我担心这是否会导致性能下降。有没有更好的方法
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://api.openweathermap.org/data/2.5/weather?lat=35&lon=139'
}, 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();
delayTwoSecs
函数,您可以使用该函数bluebird
,而不是getWeather
,并直接使用适当的函数,在本例中为getAsync
var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'));
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139';
(function loopFetching() {
request.getAsync(url)
// We get the first element from the response array with `.get(0)`
.get(0)
// and the `body` property with `.get("body")`
.get("body")
.then(console.log.bind(console))
.delay(2000)
.then(loopFetching)
.catch(console.err.bind(console));
})();
对于定期请求,这称为setInterval()
你的嵌套调用太复杂了。改为使用setInterval()
只有在前一次呼叫成功时,我才需要启动下一次呼叫。我还需要确保在过渡期间有持续的延迟。setInterval不会处理以上两种情况我想..天啊。为什么在
setInterval()
中使用字符串?@jsri您是否尝试过动态构建setInterval()
命令?你就是这样做的。@FactoryAidan:不,不是。我甚至怀疑这是否有效,因为node.js中的getWeather
不是全局的。这在功能和性能方面与问题中的代码相同,对吗?@Cyril我看不出任何理由担心这两种方法的性能。您可以更改。然后使用.get(0)更改(函数(响应){response[0].body}
。然后(函数(body){…
也可以-也可以链接承诺。
var request = require('request');
var Promise = require('bluebird');
var getWeather = function() {
return new Promise(function(resolve, reject) {
request({
method: 'GET',
uri: 'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139'
}, function(error, response, body) {
if (error) {
reject(error);
} else {
resolve(body)
}
});
});
};
var my_interval = setInterval("getWeather()",2000);