Node.js Twitter API游标
我正在使用npm-twit获取特定帐户的关注者。
Twitter API从单个GET请求返回多达5000个结果。
如果我查询的用户有超过5000个关注者,则会返回一个“next_cursor”值。
要获得下一个5000个结果,我需要重新运行GET函数,并将“next_cursor”值作为parameter passing给它。 我似乎无法弄清楚如何去做。
我正在想一个while循环,但我不能重置全局variables,我想是因为范围:
var cursor = -1 while ( cursor != 0 ) { T.get('followers/ids', { screen_name: 'twitter' }, function (err, data, response) { // Do stuff here to write data to a file cursor = data["next_cursor"]; }) }
显然,我不是一个JS天才,所以任何帮助将不胜感激。
你遇到的问题是由于Node.js是asynchronous的 。
T.get('followers/ids', { screen_name: 'twitter' }, function getData(err, data, response) { // Do stuff here to write data to a file if(data['next_cursor'] > 0) T.get('followers/ids', { screen_name: 'twitter', next_cursor: data['next_cursor'] }, getData); }) }
请注意:
- 我给了内部callback函数的名字。 这是我们可以recursion地从内部调用它。
- 循环被recursioncallbackreplace。
- 如果存在next_cursor数据,则使用相同的函数
getData
调用T.get
。
请注意, 在这里做的东西代码将被执行很多次(尽可能多的下一个游标)。 由于是recursioncallback – 订单是有保证的。
如果你不喜欢recursioncallback的想法,你可以通过以下方法避免它:
- 如果可能,事先查找所有next_cursor ,并使用for循环生成请求。
- 或者,使用asynchronous辅助模块,如asynchronous (虽然为了学习的目的,我会避免模块,除非你已经stream利的概念已经)。
考虑用一些5K +帐户进行testing。
const T = new Twit(tokens) function getFollowers (screenName, followers = [], cur = -1) { return new Promise((resolve, reject) => { T.get('followers/ids', { screen_name: screenName, cursor: cur, count: 5000 }, (err, data, response) => { if (err) { cur = -1 reject(err) } else { cur = data.next_cursor followers.push(data.ids) if (cur > 0) { return resolve(getFollowers(screenName, followers, cur)) } else { return resolve([].concat(...followers)) } } }) }) } async function getXaqron () { let result = await getFollowers('xaqron') return result } console.log(getXaqron().catch((err) => { console.log(err) // Rate limit exceeded }))
与这个一起奋斗..一切似乎工作,但数据['next_cursor']没有改变,永远!
代码应该是这样的:
T.get('followers/ids', { screen_name: 'twitter' }, function getData(err, data, response) { // Do stuff here to write data to a file if(data['next_cursor'] > 0) T.get('followers/ids', { screen_name: 'twitter', cursor: data['next_cursor'] }, getData); }) }
Twit的参数不是“next_cursor”,它只是“光标”;)