【问题标题】:How to implement a callback function while using the twitter api on Node.js如何在 Node.js 上使用 twitter api 时实现回调函数
【发布时间】:2016-07-30 05:07:59
【问题描述】:

我正在使用 twitter api 尝试获取特定用户的推文和提及,但是我一次只能获取一组特定的推文。根据我看到的类似问题,需要一个回调函数来解决这个问题,但是我很挣扎,因为我对 node.js 还很陌生。我的问题是我有两个用于推文和提及的 client.gets,但我一次只能调用一个,因此需要一个回调函数。

 jsonx = {};
  function mentions(x){
    client.get('search/tweets', {q:"@"+x, count:1},
    function (err,data){
      for(var index in data.statuses){
        var tweet = data.statuses[index];
        console.log(tweet.text);
        jsonx[index] = tweet
      }
      res.end(JSON.stringify(jsonx))
    })
  }


  function tweets(y){
    client.get('statuses/user_timeline', {screen_name:"@"+y, count:1},
    function(err,data) {
      for(var index in data){
        var tweet = data[index];
        console.log(tweet.text);
        jsonx[index] = tweet

      }
           res.end(JSON.stringify(jsonx));
    })
  }

关于如何实现回调函数以便同时从推文和提及中获取所有查询的任何帮助。

谢谢 史蒂夫

【问题讨论】:

  • 不可能有一个回调函数同时响应两个不同的 client.get 调用。你能告诉我你为什么要这样做吗,也许我可以提出一个解决方法?
  • @DevJyotiBehera 我想收集从这两个函数获得的所有推文并将其添加到同一个 JSON 对象中。

标签: javascript node.js twitter callback


【解决方案1】:

使用一个使用 Promises 的 twitter 客户端,甚至只是“承诺”你现在拥有的库,这一切都会变得非常容易。

我推荐 Bluebird.js 来做这件事。如果你要走那条路,这就是它的工作方式:

1) 需要 promise 库(通过 npm 安装后)

var Promise = require('bluebird');

2) 使用 Bluebird 的 promisify 方法创建一个新函数来发出请求。

var clientGet = Promise.promisify(client.get, client);

3) 使用聚合的 Promise 方法同时发出两个请求,例如join

Promise.join(
    clientGet('search/tweets', {q:"@"+x, count:1}),
    clientGet('statuses/user_timeline', {screen_name:"@"+y, count:1}),
    function(tweets, timeline) {
        //other stuff here, including res.end/json/send/whatever
    }
)

【讨论】:

    【解决方案2】:

    由于您想将两个函数的结果存储在单个对象中,您可以使用async 模块作为最佳实践。

    var async = require('async');
    
    async.series([
      function(_cb){
        //call function 1 here and fire _cb callback
      },
      function(_cb){
        //call function 2 here and fire _cb callback
      }
    ], function(error, response) {
      if(e) {
        //handle error
      }
      else {
        //handle response object here. It will be an array of responses from function_1 and function_2
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 2012-01-12
      • 2020-06-04
      • 2011-06-27
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多