Saturday 18 March 2017

JSON - Wait for loop to finish and then pass data to callback

I'm having a serious issue with Node.js
I'm developing an API to get back data from Facebook Databases using GraphQL and then send back JSON with selected data.

The issue comes when I iterates (with a for loop) through the response array to select the useful data, I don't know how to get all the data and then send it to client. I thought that calling the callback at each iteration would be nice but it didn't solve the problem

Here is the code from my API

Read data from GraphQL
FB.api('me/feed', ...) returns an array of all the data.
The second call returns individual post details, this is the most important part (I have to return an array of this details to the client in json format)

module.exports = function (start, end, callback) {
  if (start > end) throw 'Start is greater than end';

  FB.api('me/feed', function (res) {
    // Error handling
    if (!res || res.error) {
      throw 'FB error occurred: ' + res.error;
    }
    console.log('FB: OK');

    for (let i = start; i < res.data.length && i != end; i++) {
      FB.api(res.data[i].id + '/attachments', function(post) {
        callback({
          id: res.data[i].id,
          type: post.data[0].type,
          postDesc: res.data[i].message.split('\n\n')[0],
          postUrl: post.data[0].url,
          imagePreviewUrl: post.data[0].media.image.src
        });
      });
    }
 });
}



via Andrea Busà

No comments:

Post a Comment