Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop in Javascript with a Callback

I am trying to write the Pseudocode given here https://dev.twitter.com/docs/misc/cursoring with javascript using node-oauth https://github.com/ciaranj/node-oauth. However I am afraid because of the nature of the callback functions the cursor is never assigned to the next_cursor and the loop just runs forever. Can anyone think a workaround for this?

module.exports.getFriends = function (user ,oa ,cb){
  var friendsObject = {};
  var cursor = -1 ;
  while(cursor != 0){
    console.log(cursor);
      oa.get(
        'https://api.twitter.com/1.1/friends/list.json?cursor=' + cursor + '&skip_status=true&include_user_entities=false'
        ,user.token //test user token
        ,user.tokenSecret, //test user secret
        function (e, data, res){
          if (e) console.error(e);
          cursor = JSON.parse(data).next_cursor;
          JSON.parse(data).users.forEach(function(user){
            var name = user.name;
            friendsObject[name + ""] = {twitterHandle : "@" + user.name, profilePic: user.profile_image_url};
          });        
          console.log(friendsObject);   
        }
      );
    }  
  }
like image 408
s_curry_s Avatar asked Mar 22 '23 20:03

s_curry_s


1 Answers

Suppose your code is wrapped in a function, I'll call it getFriends, basically it wraps everything inside the loop.

function getFriends(cursor, callback) {
  var url = 'https://api.twitter.com/1.1/friends/list.json?cursor=' + cursor + '&skip_status=true&include_user_entities=false'
  oa.get(url, user.token, user.tokenSecret, function (e, data, res) {
    if (e) console.error(e);
    cursor = JSON.parse(data).next_cursor;
    JSON.parse(data).users.forEach(function(user){
      var name = user.name;
      friendsObject[name + ""] = {twitterHandle : "@" + user.name, profilePic: user.profile_image_url};
    });        
    console.log(friendsObject);
    callback(cursor); 
  });
}

In nodejs all io is done asynchronously, so you will loop a lot more than needed, before actually changing cursor, what you need is loop only when you receive a response from the Twitter API, you could do something like this:

function loop(cursor) {
  getFriends(cursor, function(cursor) {
    if (cursor != 0) loop(cursor);
    else return;
  });
}

You start it by calling loop(-1), of course this is just one way of doing it.

If you prefer you could use an external library, like async.

like image 180
Alberto Zaccagni Avatar answered Apr 05 '23 19:04

Alberto Zaccagni