0

I need to return a value from one function to another function.I have a function that is used to check whether the access_token is expired or not. If expired, it will call another function to return an refresh token.

Below function will check whether access-token is expired or not. If so, it will call another function to return an refresh token.

export function check_expires(){
  let expires_token = JSON.parse(localStorage.getItem('expires_token'))
  let uid = JSON.parse(localStorage.getItem('id'))
  if (new Date().getTime()/1000  <  expires_token){
    const a = getNewAccessToken()
  }
}

This function has to return an refresh token that's been stored in firebase.

export function getNewAccessToken() {
 let uid = JSON.parse(localStorage.getItem('id'))
 let refresh_token = ''
 firebase.database().ref('users/'+uid).on("value", snap => {
    refresh_token = snap.val().refresh_token
    let access_token = snap.val().access_token
 })
 return refresh_token
}

But console.log(refresh_token), gives me an empty string. How to return this refresh_token value from getNewAccessToken() to check_expires().

Thananjaya S
  • 1,451
  • 4
  • 18
  • 31

1 Answers1

0

You are not waiting for callback to complete and returning the result immediately. You need to chain the Async call.

You can use Promise to chain the async call.

getNewAccessToken:

export function getNewAccessToken() {

  return new Promise((resolve, reject) => {

    let uid = JSON.parse(localStorage.getItem('id'))
    let refresh_token = ''
    firebase
      .database()
      .ref('users/' + uid)
      .on("value", snap => {
        refresh_token = snap
          .val()
          .refresh_token
        let access_token = snap
          .val()
          .access_token;

          resolve(access_token);
      })

      //hanlded rejection status
  })
}

check_expires :

export function check_expires(){
  let expires_token = JSON.parse(localStorage.getItem('expires_token'))
  let uid = JSON.parse(localStorage.getItem('id'))
  if (new Date().getTime()/1000  <  expires_token){
     getNewAccessToken().then((access_token)=>{

      console.log(access_token)
     }).catch((reason)=>{

      console.log(reason);
     })
  }
}
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53