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

181
Vistas
Callback function returning promise instead of the value

I'm using fetch to grab data from a json file. In a .then(), I call a callback to do something with that data, and then eventually return the final value from the callback. The problem is that, when I return, it returns a promise instead of the final value. I've looked through other similar questions, and thought I had the asynch concepts down, but I'm still stuck on this. Is there something I'm missing?

const func = (callback) => {
  fetch('https://asdf.json')
    .then(response => {
      return response.json();
    })
    .then(data => {
      return callback(data)
    }
}
const callBack = (parsedData) => {
  //do something to get finalValue
  return finalValue
}

func(callBack);

I should add that, I tried just calling callback(data) without the return, but this just returned undefined.

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

0

fetch method returns a promise, so you must use async/await or then() to make it works properly. For example:

const func = (callback) => {
   return fetch('asdf.json')
      .then(response => {
        return response.json();
      })
      .then(data => {
        return callback(data)
      })
  }
  const callBack = (parsedData) => {
    //do something to get finalValue
    return parsedData;  
  }
  
 const main = async () => {
    console.log(await func(callBack));
 }

 main();

Using then():

const func = (callback) => {
   return fetch('asdf.json')
      .then(response => {
        return response.json();
      })
      .then(data => {
        return callback(data)
      })
  }
  const callBack = (parsedData) => {
    //do something to get finalValue
    return parsedData;  
  }
  
  func(callBack).then(response=> {
      console.log(response);
  })
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