Twitter API and Node
Twitter API and Node
我正在尝试从Twitter上检索我的最后一条推文 https://github.com/jdub/node-twitter
我想声明一个变量,在函数内更改该变量,然后在该函数外再次使用它。这可能吗?
我已经通过身份验证,如果我这样做,可以看到我的最后一条推文:
var tweet;
twit.get('http://api.twitter.com/1/statuses/user_timeline.json', function(data) {
tweet = data[0].text;
console.log(tweet);
});
但是我想将我的代码分离出来并执行以下操作:
var tweet;
twit.get('http://api.twitter.com/1/statuses/user_timeline.json', function(data) {
tweet = data[0].text;
});
console.log(tweet);
推文仍未定义。
请教育我:-)
您希望能够立即控制台.log但node.js不是同步的,这就是它如此强大和快速的原因。 您必须习惯使用 node.js 进行编码的异步模式。 获取请求是异步的。 在回调发生之前,不会分配推文。
控制台.log 在发出异步请求后立即执行。
尝试:(编辑 - 我建议这样做,然后编辑问题以包含此代码)
twit.get('http://api.twitter.com/1/statuses/user_timeline.json', function(data) {
tweet = data[0].text;
console.log(tweet); // executed after call returns
});
// executes immediately after request is sent
console.log("request sent");
请注意,twit.get 调用的第二个参数是一个匿名函数,它将在完成异步请求后执行。
此输出应为"请求已发送",然后推文按该顺序生成。
相关文章:
- node.js instanceof and cleartextStream
- Node res.write() and fs.readFile
- RegExp and Node JS
- Twitter API and Node
- Node.js and SQLite3
- rapheal js Element.node.onclick() and Element.click()
- Moongose, expressjs and node-webkit
- module.exports scope and node-mysql
- Node.js and Express - 将JSON对象从SoundCloud API发送到前端使其成为字符串
- Node.js and postgres LISTEN
- Working with Node and MySQL
- app.get and app.post get value in node.js
- Facebook OG Meta with Angular and Node
- Getting started with Node.js and JavaScript
- Ajax call and node.js
- Node.js and xlsjs or exceljs
- async.parallel on mongodb and Node.js
- Javascript, Node, Promises, and recursion
- sqlite3 and node-js returns undefined
- 如何在Node AND浏览器中使用相同的库,同时保持库的模块化