【问题标题】:While loop with javascript使用 javascript 循环
【发布时间】: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


【解决方案1】:

async.whilst 使用回调来了解您的“worker”函数何时完成处理,因此请记住始终调用async.whilst 传递给函数的callback 参数,当您准备好时将其作为第二个参数提供给函数用于“循环”的下一个循环。

【讨论】:

    【解决方案2】:

    我认为缺少的是“进程”函数中的回调

    类似:

    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;
                      callback(null, cursor );
                    }
              )
          },
          function(){
              console.log(cursor);//should print 0
          }
    )
    

    注意 null 因为第一个参数 seance err 是一种标准。

    希望这对某人有所帮助。 问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      相关资源
      最近更新 更多