I have a question. I’ve been trying to figure this out for the past 3 hours now, and I have no clue as to why this isn’t working how i’m expecting it to. Please know that i’m still very new to Javascript, so I apologise if anything is blatantly obvious.
With this code, i’m trying to get a bearer token from Twitter, however, return body
and console.log(body)
return 2 completely different things.
When I console.log(body)
, I get the output I expect:
{"token_type":"bearer","access_token":"#####"}
However, if I return body
, I get the http request as JSON. I’ve pasted my code below, I hope someone will be able to help.
var request = require('request'); var enc_secret = new Buffer(twit_conkey + ':' + twit_consec).toString('base64'); var oauthOptions = { url: 'https://api.twitter.com/oauth2/token', headers: {'Authorization': 'Basic ' + enc_secret, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}, body: 'grant_type=client_credentials' }; var oauth = request.post(oauthOptions, function(e, r, body) { return body; }); console.log(oauth)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Async, async, async.
You cannot return the results of an asynchronous operation from the function. The function has long since returned before the asynchronous callback is called. So, the ONLY place to consume the result of your request.post()
is INSIDE the callback itself and by calling some other function from within that callback and passing the data to that other function.
var oauth = request.post(oauthOptions, function(e, r, body) { // use the result here // you cannot return it // the function has already returned and this callback is being called // by the networking infrastructure, not by your code // you can call your own function here and pass it the async result // or just insert the code here that processes the result processAuth(body); }); // this line of code here is executed BEFORE the callback above is called // so, you cannot use the async result here
FYI, this is a very common learning issue for new node.js/Javascript developers. To code in node, you have to learn how to work with asynchronous callbacks like this.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0