Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda