Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda