javascript - Recursive asynchronous api calls - Stack Overflow

I'm working on an project that requires me to use the twitter api. Trying to return all the follow

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 e 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
})

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 e 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
})
Share Improve this question edited May 27, 2017 at 6:36 Leon asked May 27, 2017 at 6:30 LeonLeon 1242 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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');
})

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).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745654642a4638470.html

相关推荐

  • javascript - Recursive asynchronous api calls - Stack Overflow

    I'm working on an project that requires me to use the twitter api. Trying to return all the follow

    8小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信