1

I'm working on an project that requires me to use the twitter api. Trying to return all the followers of a given user. The problem is getting all the user bc twitter separate followers into blocks of at most 200.

I saw a solution online that they call the callback recursively, however I'm getting stuck trying to use promises to get all the data back before proceeding. Currently it waits for the first page to come back but idk how to make it wait for all the promises to return. Can someone give me any hints/tips and if theres a way to do this iteratively?

let cursor = -1;
let promise = new Promise((resolve,reject)=>{
      twitter.followers({cursor},function callback(data, error){
       if(error)
           reject(false)
      cursor = data.next_cursor;
      if(cursor!=0){
           new Promise((resolve,reject)=>{
                twitter.followers({cursor},callback)
           })
           resolve(true);
      }
})
})
promise.then({
    //do stuff
})

2 Answers 2

2

You're close, but your approach just needs a few adjustments:

  • When there is an error, don't do anything else than reject()
  • Don't create a new, nested promise, but work with the current one: delay any call of resolve() (or reject()) until the next callback is invoked.
  • Only resolve() when the cursor has reached 0.
  • The final then needs a callback argument, not an object literal.

Here is the adjusted code (with a dummy implementation of twitter.followers to make it work):

// Mock implementation, for the snippet to work:
var twitter = {
    followers: function (obj, callback) {
        setTimeout(function () {
            callback({
                next_cursor: (obj.cursor + 5) % 6
            }, 0);
        }, 100);
    }
}

let cursor = -1;
let promise = new Promise((resolve,reject)=>{
    twitter.followers({cursor}, function callback(data, error){
        if (error) {
            reject(false)
            return; // Don't continue after error
        }
        cursor = data.next_cursor;
        console.log(cursor);
        if (cursor != 0){
            // Don't create a new promise, just delay to resolve
            twitter.followers({cursor}, callback)
            return; // don't resolve now
        }
        resolve(true);
    })
})
promise.then(function () { // You need a callback function here
    console.log('all done');
})

1

First, make a function that gets some data and returns a promise. I'm not sure exactly what yours would be like, but perhaps something like this:

function getFollowers(args) {
    return new Promise((resolve, reject) => {
        twitter.followers(args, function(data, error) {
            if (error) {
                reject(error);
            } else {
                resolve(data);
            }
        });
    });
}

Then, you can call that function recursively from within a .then() handler and return the new promise from the .then() handler to automatically chain it onto the previous promise.

function getAllFollowers(user) {
    return getFollowers(...).then(data => {
         if (data.next_cursor) {
             return getFollowers(...).then(data => {
                 // collect data here
             });
         } else {
             return accumulated_data;
         }
    });
}

getAllFollowers(...).then(data => {
    // got all data here
}).catch(err => {
    // error here
});

Note, this is partly pseudo-code because I don't follow the exact logic you're trying to implement or the APIs you're using. But, the general idea is that you can recursively return a new promise from within the .then() handler and that will automatically chain that onto the previous promise.

If you want to accumulate some data from all the calls, then you need to also do that in a .then() handler from the recursive call so you are accumulating the total data you want (you don't show anything about what type of result you're trying to collect so this code doesn't show that).

4
  • You're awesome! This exactly the logic I was looking for but for some reason I just couldn't come up with it myself.
    – Leon
    May 27, 2017 at 6:49
  • 1
    Actually I'm still a little confused. How the recursive step would work? From the pseudocode it seems like there's only two calls of getFollowers being made.
    – Leon
    May 27, 2017 at 6:52
  • wait, I think you meant to put getAllFollowers instead of the getFollowers am I right?
    – Leon
    May 27, 2017 at 7:00
  • @Leon - That depends upon what you're trying to do. I don't understand how you want the recursive logic to work. You decide.
    – jfriend00
    May 27, 2017 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.