尝试使用带有 twit 节点模块的 MeteorJS,错误:[TypeError: Object #<Object>没有方法“请求"] [英] Attempting to use MeteorJS w/twit Node Module, Error: [TypeError: Object #<Object> has no method 'request']

查看:29
本文介绍了尝试使用带有 twit 节点模块的 MeteorJS,错误:[TypeError: Object #<Object>没有方法“请求"]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用带有 twit Node 模块的 MeteorJS 来访问推文的屏幕名称.仍然只是测试代码,看看我是否可以从 Twitter 检索 JSON.

So I'm using MeteorJS w/the twit Node module to access the screen name of a tweet. Still just testing the code to see if I can retrieve the JSON from twitter.

这是我的代码:

  var Tget = Meteor.wrapAsync(T.get);

  Meteor.methods({
    'screenName' : function() {
      try {
        var result = Tget('search/tweets', {q:'#UCLA',count:1});
        JSON.stringify(result);
        console.log(result);
      }
      catch (e) {
        console.log(e);
        return false; 
    }
  }
  })

我收到的错误是:

  [TypeError: Object #<Object> has no method 'request']

这是 twit 模块 git:https://github.com/ttezel/twit/blob/master/README.md

Here is the twit module git : https://github.com/ttezel/twit/blob/master/README.md

推荐答案

我想我明白了.这是T.get的代码:

I think I understand. Here's the code of T.get:

Twitter.prototype.get = function (path, params, callback) {
  return this.request('GET', path, params, callback)
}

如您所见,它期望 this 具有方法 request.然而,因为我们使用了 wrapAsync 而不关心执行上下文(使用 this 访问),失败.

As you can see, it expects this to have the method request. However, because we used wrapAsync without caring about the execution context (accessed with this), it fails.

考虑这个例子(您可以在浏览器控制台中复制/粘贴):

Consider this example (you can copy/paste that in your browser console):

var obj = {
  foo : 'foo',
  logThis : function() {
    console.log(this);
  }
};

如果我们执行 obj.logThis() 我们有: Object { foo: "foo", logThis: obj.logThis() }
但是如果我们执行以下操作...

If we execute obj.logThis() we have: Object { foo: "foo", logThis: obj.logThis() }
But if we do the following...

var otherLogThis = obj.logThis;
otherLogThis();

它记录了 Window 对象,因为我们从它的上下文中获取了函数!

It logs the Window object because we got the function out of its context!

如何解决这个问题?绑定函数?棘手的电话?
不,Meteor 有解决方案.
wrapAsync 可以有两个参数... 第二个是上下文!

How to solve that issue? Binding the function? Tricky call?
Nope, Meteor has the solution. wrapAsync can have two parameters... The second one is the context!

var Tget = Meteor.wrapAsync(T.get, T);

<小时>

如果你想了解更多关于 JavaScript 上下文的知识,我推荐这本书:
https://github.com/getify/You-Dont-Know-JS/
它是免费和开源的,除了我最深的感情和温柔的回忆,当我阅读它时,我的大脑以各种有趣的方式在成长,我没有任何关联.

这篇关于尝试使用带有 twit 节点模块的 MeteorJS,错误:[TypeError: Object #&lt;Object&gt;没有方法“请求"]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆