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

146
Vistas
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 Respuestas
Responde la pregunta

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 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