Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda