Nodejs Request Return Misbehaving

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:


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: '',
    headers: {'Authorization': 'Basic ' + enc_secret, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
    body: 'grant_type=client_credentials'

var oauth =, function(e, r, body) {
    return body;



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 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 =, 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

// 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 or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x