Node.js Twitter API游标 [英] Node.js Twitter API cursors
问题描述
我正在使用 npm-twit 来获取特定帐户的关注者。
I'm using npm-twit to get followers of a specific account.
Twitter API从单个GET请求返回最多5000个结果。
The Twitter API returns up to 5000 results from a single GET request.
如果我查询的用户有超过5000个关注者,则返回带有数据的next_cursor值。
If the user I'm querying has over 5000 followers a "next_cursor" value is returned with the data.
要获得接下来的5000个结果,我需要重新运行GET函数,并将next_cursor值作为参数传递给它。我似乎无法理解如何做到这一点。
To get the next 5000 results, I need to re-run the GET function, passing it the "next_cursor" value as an argument. I just can't seem to work out how to do it.
我在想一个while循环,但是我无法重置全局变量,我认为是因为范围:
I was thinking a while loop, but I can't reset the global variable, I think because of scope:
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的天才,所以任何帮助都会非常感激。
Obviously I'm not a JS genius, so any help would be much appreciated.
推荐答案
您遇到的问题是由于Node.js 异步。
The issue you are having is due to Node.js being 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);
})
}
请注意:
- 我给内部回调函数命名。这样我们就可以从内部递归调用它。
- 循环被替换为递归回调。
- 如果有next_cursor数据,然后我们使用相同的函数
getData
调用T.get
。
- I gave a name to the internal callback function. That is so that we can recursively call it from the inside.
- The loop is replaced with a recursive callback.
- If there is a next_cursor data, then we call
T.get
using the same functiongetData
.
请注意这里的东西代码将被执行多次(与下一个游标一样多)。因为它是递归回调 - 订单是有保证的。
Be aware that Do stuff here code will be executed many times (as many as there are next cursors). Since it is recursive callback - the order is guaranteed.
如果你不喜欢递归回调的想法,你可以通过以下方式避免它:
If you do not like the idea of recursive callbacks, you can avoid it by:
- 如果可能,事先找出所有 next_cursor ,并使用 for loop。
- 或者,使用异步辅助模块,如异步(虽然出于学习目的,我会避免使用模块,除非你已经熟悉这个概念)。
- Finding out beforehand all the next_cursor's if possible, and generate requests using for loop.
- Alternatively, use asynchronous-helper modules like Async (though for learning purposes, I would avoid modules unless you are fluent in the concept already).
这篇关于Node.js Twitter API游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!