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

207
Views
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 answers
Answer question

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 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!