Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
In my code I got undefined while function returns true

Function Definition

export const checkAuth = (accessToken) => {
const url = 'https://example/user-profile';
    console.log("We are in outer function");
    fetch(url, {
        method: 'GET',
        headers: new Headers({
            'Authorization' : 'Bearer ' + accessToken,
        })
    }).then(res => res.json())
        .catch(function(error){
            console.error('Error : ', error)
        })

    .then((response) => {
            if(response.error != 'Unauthorized')
            {
                return true;
            }
            else{
                return false;
            }
    })
}

Function Calling

var res=checkAuth(this.state.accessToken);

In the res variable, I got undefined but I am passing true. How can I solve the problem?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The checkAuth function isn't returning a value from the function. You are returning a value from the Promise chain, but that is the value that should be returned from checkAuth. You can simply return the Promise that fetch returns.

export const checkAuth = (accessToken) => {
  const url = 'https://example/user-profile';
  console.log("We are in outer function");
  return fetch(url, {
    method: 'GET',
    headers: new Headers({
      'Authorization' : 'Bearer ' + accessToken,
    })
  }).then(res => res.json())
    .catch(function(error){
      console.error('Error : ', error)
    })
    .then((response) => {
      return response.error != 'Unauthorized'
    });
}

Because checkAuth now returns a Promise you will need to either call it in an async function and await the Promise to resolve, or chain from the returned Promise.

checkAuth(this.state.accessToken)
  .then(value => {
    // do something with value
  })
  .catch(error => {
    // handle any Promise rejections if they occur
  });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda