递归调用异步函数

时间:2015-03-02 07:04:50

标签: javascript node.js promise bluebird

我需要一个异步方法,例如。 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();

2 个答案:

答案 0 :(得分:3)

  1. 您不需要delayTwoSecs功能,您可以使用Promise.delay功能。

  2. 您可以使用getWeatherPromisify所有函数代替bluebird,并使用正确的函数,在本例中为getAsync。< / p>

  3. 所以,你的程序就像这样

    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));
    })();
    

    这称为Immediately Invoking Function Expression.

答案 1 :(得分:-1)

用于重复请求的setInterval()

你使用嵌套调用过度复杂化了。改为使用setInterval()。

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);
相关问题