0

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}`)  
});
Josh Simon
  • 159
  • 1
  • 10
  • 27

1 Answers1

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.

Divyesh Parmar
  • 321
  • 1
  • 6
  • 15