0

what I need is to on my server-side(Node.js), make something like this:

$.when(
            $.get("https://graph.facebook.com/341446932600922/posts?fields=message,created_time&limit=2", function (dataAcib) {
                allPosts.acib = dataAcib.data;
            }),
            $.get("https://graph.facebook.com/599914540070454/posts?fields=message,created_time&limit=2", function (dataBlusoft) {
                allPosts.blusoft = dataBlusoft.data;
            })
        ).then(function () {
            $.each(allPosts, function () {
                for (i = 0; i < this.length; i++)
                {
                    $("#divNoticias").append("<p>" + this[0].message + "</p>");
                }

                //- console.log(this[0].message);
            });

            console.log(allPosts);

            var posts = $.makeArray(allPosts.data);
            console.log(posts);
        });

I want to accomplish this on server side so that I can send the result to my client-side.

I've used Requestify, and succeded on getting the data of ONE request, but I want to do all my requests (total of 6) assynchronously and when they are finished, procced to the callback.

How can I make all those GET calls and when ALL they are done, do a callback on node server-side?

Thanks

1 Answers1

0

Note: I have never used Requestify before but I'll take a crack at it based on their documentation.

When working with async, I like to use async.js as it is very useful. We can use it to map each URL to their responses.

var async = require('async'),
    requestify = require('requestify');

var urls = [
    'https://graph.facebook.com/341446932600922/posts?fields=message,created_time&limit=2',
    'https://graph.facebook.com/599914540070454/posts?fields=message,created_time&limit=2'
];
// loop through each URL
async.mapSeries(urls, function (url, done) {
    // for a particular URL, make the request
    requestify.get(url).then(function (response) {
        // pass the response
        done(null, response);
    });
// when all URLs are done
}, function (err, responses) {
    // responses should be an array e.g. [response, response]
    // now do something with responses
});

Edit

I don't know what kind of data you are getting back from Facebook. For each operation, you could adjust the code by passing only the data you need.

async.mapSeries(urls, function (url, done) {
    // for a particular URL, make the request
    requestify.get(url).then(function (response) {
        // pass the response data
        done(null, response.data);
    });
// when all URLs are done
}, function (err, responses) {
    // responses should be a multi-dimensional array e.g. [[data], [data]]
    // here, you could merge and flatten them
    responses = [].concat.apply([], responses);
    console.log(responses);
    // now do something with responses
});

Merge and flattening logic came from this answer

Community
  • 1
  • 1
Mikey
  • 6,728
  • 4
  • 22
  • 45