Home > Net >  how to wait on a promise and return it's value on a callback
how to wait on a promise and return it's value on a callback

Time:03-12

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.

CodePudding user response:

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.

  • Related