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

136
Visualizações
how to wait on a promise and return it's value on a callback

I need help understanding how this work please.

I have a requestAssistant.js file that has all the API call functions my app will need. I have a function :

export async function retreiveTodoTest(testId){
const options ={
    method: 'GET',
}

const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${testId}`, options);
const json = await response.json();

console.log(json);

return json;    
}

now in my index.js file, I am trying to call that function :

app.get('/todos/:id', (req, res)=>{
const myId = req.params.id;
retreiveTodoTest(myId)
.then(response => response.json())
.then(json =>{
    console.log(json);
    res.json({result: json})
})     

} but I keep getting an error : TypeError: response.json is not a function

I also tried:

app.get('/todos/:id', (req, res)=>{
const myId = req.params.id;
const response = retreiveTodoTest(myId)
response.then(result =>{
  res.json({message:'success', data: result})
})     
}

it not returning anything. I tried to print 'response' to see if my retreiveTodoTest returned any value but I am getting Promise. What I am doing wrong. I know the return statement will execute before the Promise but how can I bring the value into the index.js file. Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is because you are already awaiting the json and returning it.

async function retreiveTodoTest(testId){
    const options ={
        method: 'GET',
    }
    
    const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${testId}`, options);

    return response
}

Or you can remove the .then(response => response.json()) either one works.

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