【发布时间】:2014-12-25 07:36:07
【问题描述】:
我正在探索 node.js 异步库以在 node.js 中实现游标 (https://dev.twitter.com/docs/misc/cursoring)。
whilst 看起来像我正在寻找的功能,但我的情况有点不同。每次我发出GET 请求时,我都必须等待得到响应,然后更改光标值。
在async 文档中,这是为whilst 给出的示例
var count = 0;
async.whilst(
function () { return count < 5; },
function (callback) {
count++;
setTimeout(callback, 1000);
},
function (err) {
// 5 seconds have passed
}
);
我尝试做类似的事情来实现 twitter 光标导航,但它似乎不起作用:
async.whilst(
function(){return cursor != 0},
function(callback){
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);
console.log("I AM HERE");
cursor = JSON.parse(data).next_cursor;
}
)
},
function(){
console.log(cursor);//should print 0
}
)
编辑: 我的 get 请求回调中的 console.log("I AM HERE") 只被调用一次,之后什么也没有发生..
我不认为中间的函数应该有一个回调来改变计数器,whilst 只有在计数器在实际函数中而不是在它的回调中改变时才有效..
【问题讨论】:
-
stackoverflow.com/questions/18156937/… 这里给出了不使用异步的答案..
-
您能否详细说明“它似乎不起作用”?运行脚本时看到什么错误?
-
关于您的编辑,可以让回调修改
counter变量。您可以尝试在回调中打印data以查看您从 twitter 获得的响应吗? -
数据打印它应该打印的内容,20 个 twitter 用户和 {"next_cursor":1442041778886213517,"next_cursor_str":"1442041778886213517","previous_cursor":0,"previous_cursor_str":"0"}
-
将
callback();添加到您传递给oa.get()的回调末尾。
标签: javascript node.js twitter async.js