skip to Main Content

I am using Facebook Graph NodeJS API to fetch user_posts. The response has pagination and therefore I need to loop over the response to fetch all the posts. I am using following route to fetch facebook posts and I am looping over pagination using get_user_statuses function:

var posts = "";

function get_user_statuses(response_posts, res) {

    var link_regex = /https?://(?:www.|(?!www))[^s.]+.[^s]{2,}|www.[^s]+.[^s]{2,}/g;
    var isNextPageAvailable = true;

    if ("paging" in response_posts) {
        var nextPage = response_posts.paging.next;
        isNextPageAvailable = true;

    } else {
        isNextPageAvailable = false;
    }

    for (var i = 0; i < response_posts.data.length; i++) {

        var post = response_posts.data[i].message + " ";

        if ("message" in response_posts.data[i]) {
            posts += post.replace(link_regex, "");
        }
    }

    if (nextPage !== undefined) {
        request(nextPage, function (error, response, body) {

            if (!error && response.statusCode === 200) {
                get_user_statuses(JSON.parse(body));

            } else {
                console.log(error);
            }
        });
    }

    if (!isNextPageAvailable){
        //Sending posts to facebook Modal
        console.log(posts);
        res.send(JSON.stringify({posts: posts}));    //res is not defined here
    }
}

router.post('/fbData', function (req, response, next) {

    FB.setAccessToken(req.body.access_token);
    FB.api('/me?fields=posts&posts.limit=1000', function (res) {

        if (!res || res.error) {
            if (!res) {
                response.send(JSON.stringify({error: 'An error occurred. Please try again.'}))
            }
            response.send(JSON.stringify({error: response.error}));
            return;
        }

        get_user_statuses(res.posts, response);   //Passing response object here

    });
});

The issue is that response object passed from express route is not defined in get_user_statuses function. Now I have two question:

  1. Why is response object is not defined?
  2. Is there better approach to achieve this arrangement?

2

Answers


  1. Chosen as BEST ANSWER

    I solved my problem. I needed to create a function with a callback. In case anyone else is stuck at this kind of issue, this post helped me resolve it:

    [How to recurse asynchronously over API callbacks in node.js?


  2. res is not defined because you forgot to pass it in internal call. Change get_user_statuses(JSON.parse(body)); to get_user_statuses(JSON.parse(body), res); and it should work

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search