use*_*827 5 javascript twitter node.js
我正在使用npm-twit来获取特定帐户的关注者.
Twitter API从单个GET请求返回最多5000个结果.
如果我查询的用户有超过5000个关注者,则返回带有数据的"next_cursor"值.
为了获得接下来的5000个结果,我需要重新运行GET函数,并将"next_cursor"值作为参数传递给它.我似乎无法弄清楚如何做到这一点.
我在想一个while循环,但是我无法重置全局变量,我认为是因为范围:
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"];
})
}
Run Code Online (Sandbox Code Playgroud)
显然我不是JS的天才,所以任何帮助都会非常感激.
您遇到的问题是由于Node.js是异步的.
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);
})
}
Run Code Online (Sandbox Code Playgroud)
请注意:
T.get使用相同的函数调用getData.请注意,Do stuff here代码将被执行多次(与下一个游标一样多).由于它是递归回调 - 订单是有保证的.
如果你不喜欢递归回调的想法,你可以通过以下方式避免它:
| 归档时间: |
|
| 查看次数: |
1561 次 |
| 最近记录: |