0

hello I'm trying to setup a simple rest client to work with Axios and swagger codegen in Javascript.

I don't have much experince with javascript and i'm coming from a Java background so there might be some obvious way of doing this that i'm missing.

So before i'm able to use the API I need a token

async function get_token() {
    return await axios.post(url, data, headers)
}

Now if I want to use the token as such

token = get_token()
console.log(token)

Nothing happens because the console.log is executed before the response is recieved. I've read a bit about promises and await

Now from what i've been able to google people seem to do something like this:

token = get_token().then(function(result) {
  console.log(result)
})

This works but, then my whole rest client would have to be within this "then" block. I would much rather have a flow that looks something like this.

POST to get token.
wait for token to arrive.
initiate rest client with token.
Use the client when it's needed.

Right now I'm stuck at step 2 in the pseudo code above.

  • Once it's async, it's async *all the way down*. You can't synchronously access the result of an asynchronous operation. Transition to async at the entry point to your code (event handler, etc.), and then from that point on you can use `await` to wait for asynchronous results, throughout your code. – T.J. Crowder Aug 30 '22 at 17:14
  • Add await before calling the function like: `token = await get_token();` should solve your problem. – Warjeh Aug 30 '22 at 17:15

0 Answers0