Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
Cannot access variable inside request function JS

I have a function which should return an access token. Inside a function there is a request, which gives me the token. But I can not acces it in the main function.

Here is my code from inside a function:

var accessToken = 'test1';

 request.post(authOptions, function(error, response, body) {
    accessToken = body.access_token;    
    console.log('test2 ' + accessToken);
  });
  
  console.log('test3 ' + accessToken);

It gives the following result:

test3 test1

(node:14744) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time

(Use node --trace-warnings ... to show where the warning was created)

test2 BQDzZHO1Eg99...

The accessToken gets the value inside the request as seen in test2, but when I retrieve it after the function, it hasn't got it yet. How can I use it after? eg. in function retrieve

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

When you do request.post your code has to wait for a response from the server you are posting to. This response is handled in your function(error, response, body) function (passed in as the 2nd argument to request.post. But in the meantime the rest of your function will continue to be executed. I've added comments to try and explain this futher:

var accessToken = 'test1'; // First line of your code is executed first

// Now we execute request.post
request.post(authOptions, function(error, response, body) {
  // This is only executed whenever the response is received.  It may be many milliseconds later
  accessToken = body.access_token;    
  console.log('test2 ' + accessToken);
});

// This is executed immediately after the `request.post`.  Therefore accessToken will still be 'test1'.
console.log('test3 ' + accessToken);

Instead you can return a Promise or use callbacks to get the accessToken from this function. Here is a basic callback function:

function getAccessToken(callback) {
  request.post(authOptions, function(error, response, body) {
    callback(body.access_token);
  });
}

getAccessToken(function(myToken) {
  // Here is your token.
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!