在Javascript中循环使用回调

Gor*_*ven 4 javascript twitter node.js twitter-oauth

我试图写在这里给出的伪代码https://dev.twitter.com/docs/misc/cursoring使用节点的OAuth使用javascript https://github.com/ciaranj/node-oauth.但是我担心由于回调函数的性质,游标永远不会分配给next_cursor,循环只会永远运行.谁能想到解决这个问题?

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);   
        }
      );
    }  
  }
Run Code Online (Sandbox Code Playgroud)

Alb*_*gni 5

假设你的代码被包装在一个函数中,我会称之为getFriends,基本上它将所有内容包装在循环中.

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); 
  });
}
Run Code Online (Sandbox Code Playgroud)

在nodejs中,所有io都是异步完成的,因此你需要循环比实际更多,在实际更改之前cursor,只有当你从Twitter API收到响应时才需要循环,你可以这样做:

function loop(cursor) {
  getFriends(cursor, function(cursor) {
    if (cursor != 0) loop(cursor);
    else return;
  });
}
Run Code Online (Sandbox Code Playgroud)

你通过调用启动它loop(-1),当然这只是一种方法.

如果您愿意,可以使用外部库,如异步.