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

204
Visualizações
How do I pass result of asynchronous function to a redirect?

I have a function which is returning information from an API call,part of which is an access token. I then need to plug that access token into the parameters of a redirect URL. Only problem is that thw redirect is invoked before the data is returned. Any ideas on how I can wait till the data is returned before invoking the redirect?

Here's the code:

    oauthClient.createToken(req.url)
       .then((authResponse) => {
             oauth2_token_json = JSON.stringify(authResponse.getJson(), null,2);
             let newToken = JSON.parse(oauth2_token_json)
             accessToken = newToken.access_token
         })
        .catch((e) => {
             console.error(e);
         });

         res.redirect(`http://localhost:3000/?token=${accessToken}`)  
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Add one more .then() and make sure the previous .then() returns the authToken (or any variable). Now run that logic of res.redirect(..).. in the next nested .then().

This way you are making sure, the code waits for the asynchronous part to finish off first. then-ables are the best way to make sure your code only runs once the promise is resolved. JavaScript executioner jumps to next line of code once it sees a asynchronous code block, i.e., could be a promise, .then()s, async-awaits. This was the reason why, res.redirect() was running a little earlier.

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