Async module error with concurrent API requests

I am starting in node.js and now I am trying to get some API result. I use an asynchronous module ( https://github.com/caolan/async ) for a parallel request so that it can be optimized.

The problem is that the code returns an error, which each time points to a different line (the line "callback (error, data)" in another API call

This is mistake:

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

I use the following function to request an 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);
    });
}

To illustrate this, I use an asynchronous module:

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

Hope you help me, thanks!

+5
source share
1 answer

data (. ), , , .

Async.parallel , .

, end, .

, .

+12

All Articles