5

我是 node.js 的初学者,现在我正在尝试获得一些 API 的结果。我正在使用异步模块(https://github.com/caolan/async)来并行请求,以便对其进行优化。

问题是代码返回一个错误,每次指向不同 API 调用中的不同行(“callback(err, data)”行)

这就是错误:

if (called) throw new Error("Callback was already called.");
                          ^
Error: Callback was already called.

我正在使用以下函数来请求 API:

function getData(s, apiURL, getURL, callback) {

    var ht;
    if (s == 1) {
        ht = https;
    } else {
        ht = http;
    }

    var options = {
        hostname : apiURL,
        path : getURL,
        method : 'GET'
    }

    var content = "";

    ht.get(options, function(res) {
        console.log("Got response: " + res.statusCode);

        res.on("data", function(chunk) {

            content += chunk;
            //console.log(content);
            callback(content);
       });

    }).on('error', function(e) {
        console.log("Error: " + e.message);
        console.log(e.stack);
    });
}

为了说明,这就是我使用异步模块的方式:

var sources = sources.split(',')

    async.parallel({
        flickr : function(callback) {
            if (sources[0] == 1) {
                getData(0, 'api.flickr.com',
                "/services/rest/?method=flickr.photos.search&format=json&nojsoncallback=1&api_key=" + config.flickr.appid + "&per_page=5&tags=" + tags,

                function(data) {
                    callback(null, data); //here that the error may point
                });

            } else { callback(); }
        },
        instagram : function(callback) {
            if (sources[1] == 1) {

                getData(1, 'api.instagram.com',
                "/v1/tags/" + tags.split(',')[0] + "/media/recent?client_id=" + config.instagram,
                function(data) {                        
                    callback(null, data); //here that the error may point

                });
            } else { callback(); }
        } 
    }, function(err, results) {             
            console.log(results);
        });

希望你能帮助我,谢谢!

4

1 回答 1

12

您正在data事件内部调用回调函数(请参阅文档),每次接收到一大块数据时都会触发该回调函数,这意味着多次。

Async.parallel is expecting the callback to be executed only once for each task.

To ensure only one callback per task, put the callback on an end event, for example.

Also, the error event should execute the callback as well.

于 2013-03-30T02:10:20.280 回答