我正在尝试编写此处给出的伪代码https://dev.twitter.com/docs/misc/cursoring https://dev.twitter.com/docs/misc/cursoring使用 javascript 使用 node-oauthhttps://github.com/ciaranj/node-oauth https://github.com/ciaranj/node-oauth。然而,我担心由于回调函数的性质,光标永远不会分配给 next_cursor 并且循环会永远运行。有人能想到解决方法吗?
module.exports.getFriends = function (user ,oa ,cb){
var friendsObject = {};
var cursor = -1 ;
while(cursor != 0){
console.log(cursor);
oa.get(
'https://api.twitter.com/1.1/friends/list.json?cursor=' + cursor + '&skip_status=true&include_user_entities=false'
,user.token //test user token
,user.tokenSecret, //test user secret
function (e, data, res){
if (e) console.error(e);
cursor = JSON.parse(data).next_cursor;
JSON.parse(data).users.forEach(function(user){
var name = user.name;
friendsObject[name + ""] = {twitterHandle : "@" + user.name, profilePic: user.profile_image_url};
});
console.log(friendsObject);
}
);
}
}
假设你的代码被包装在一个函数中,我将调用它getFriends
,基本上它包含了循环内的所有内容。
function getFriends(cursor, callback) {
var url = 'https://api.twitter.com/1.1/friends/list.json?cursor=' + cursor + '&skip_status=true&include_user_entities=false'
oa.get(url, user.token, user.tokenSecret, function (e, data, res) {
if (e) console.error(e);
cursor = JSON.parse(data).next_cursor;
JSON.parse(data).users.forEach(function(user){
var name = user.name;
friendsObject[name + ""] = {twitterHandle : "@" + user.name, profilePic: user.profile_image_url};
});
console.log(friendsObject);
callback(cursor);
});
}
在nodejs中,所有io都是异步完成的,因此在实际更改之前,您将循环比需要更多的次数cursor
,你需要的是只有当你收到来自 Twitter API 的响应时才循环,你可以这样做:
function loop(cursor) {
getFriends(cursor, function(cursor) {
if (cursor != 0) loop(cursor);
else return;
});
}
你可以通过调用来启动它loop(-1)
,当然这只是一种方法。
如果您愿意,可以使用外部库,例如async https://github.com/caolan/async.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)