Home > OS >  axios return POST response outside function - Typescript
axios return POST response outside function - Typescript

Time:09-20

I'm trying to write a function in Typescript that returns a token value. Everything works perfectly up until the point where the token value is simply logged into the console and not returned.

  createToken(): string{
      axios.post(BASE_URL, body, { headers })
      .then(async (response) => {
      let responseData = response.data;
      let getToken = JSON.stringify(responseData);
      const obj = JSON.parse(getToken);
      //VALUE IS LOGGED IN THE CONSOLE, HOW CAN IT BE RETURNED??
      console.log(obj.access_token);
      })
      .catch(err => {
        console.log(err);
      })
  return 'TOKEN SHOULD BE RETURNED HERE';
  }

CodePudding user response:

Your .then() function runs after the post returns. Since that is asynchronous, it may (and almost always will) be after the function has already returned.

If you want Javascript to wait for it, you need to use the async/await format instead.

CodePudding user response:

The token cannot be returned because by the time it is retrieved in the callback, the createToken function has already finished executing. Consider rewriting your function using async/await syntax to make it return a Promise:

async createToken(): Promise<string> {
    const { data } = await axios.post(BASE_URL, body, { headers })
    return data.access_token
}

CodePudding user response:

You can do like this which you can see in the first answer post

async createToken(): Promise<string> {
    const { data } = await axios.post(BASE_URL, body, { headers })
    return data.access_token
}

But, if you don’t like to use await, You can do like this...

async createToken(): Promise<string> {
      return axios.post(BASE_URL, body, { headers })
      .then(async (response) => {
      let responseData = response.data;
      let getToken = JSON.stringify(responseData);
      const obj = JSON.parse(getToken);
      //VALUE IS LOGGED IN THE CONSOLE, HOW CAN IT BE RETURNED??
      console.log(obj.access_token);
      return obj.access_token;
      })
      .catch(err => {
        console.log(err);
      });
  } 
  • Related