如何在Node.js上使用twitter api实现回调函数

How to implement a callback function while using the twitter api on Node.js

本文关键字:api twitter 实现 回调 函数 Node js      更新时间:2024-03-12

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

 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));
    })
  }

任何关于我如何实现回调功能的帮助,以便同时从推特和提及中获得所有查询。

谢谢Steve

使用一个使用Promises的twitter客户端,甚至只是"Promiseing"您现在拥有的库,都会让这变得非常容易。

我推荐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
    }
)

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

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
  }
});