简体   繁体   English

如何等待 promise 并在回调中返回它的值

[英]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.我有一个 requestAssistant.js 文件,其中包含我的应用程序需要的所有 API 调用函数。 I have a function:我有一个 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:现在在我的 index.js 文件中,我试图调用 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但我一直收到错误消息: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.我尝试打印“响应”以查看我的 retreiveTodoTest 是否返回任何值,但我得到的是 Promise。我做错了什么。 I know the return statement will execute before the Promise but how can I bring the value into the index.js file.我知道 return 语句将在 Promise 之前执行,但如何将值带入 index.js 文件。 Thanks.谢谢。

This is because you are already awaiting the json and returning it.这是因为您已经在等待 json 并返回它。

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.或者您可以删除.then(response => response.json())中的任何一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM