【发布时间】:2022-02-09 17:09:01
【问题描述】:
我目前正在尝试从 API 中获取某些内容。但是,提取非常大,并且提取不会等待,因此即使我正在使用等待它也会返回 undefined? 我知道 fetch 可以正常工作并返回一个包含 2400 多个对象的对象。但是,这需要一段时间,问题是它不会等待。它只是返回未定义。所以 1 秒后,它会在控制台记录结果,但 React 已经完成接收未定义的内容。
app.get("/api/v1/getfrostdata",async(req,res)=>{
try{
let response = await FetchTemp();
console.log(response)
res.status(200).json({
status:"success",
data:{
timeSeries:response
}
})
}
catch(err){
console.log(err)
}
})
async function FetchTemp(){
fetch('https://frost.met.no/observations/availableTimeSeries/v0.jsonld?elements=air_temperature',{method:"get",
body: JSON.stringify(),
headers:{ Authorization: 'MY SECRET'}
})
.then(res=>res.json())
.then(async(data)=>{
console.log(data)
return data;
})
}
【问题讨论】:
-
FetchTemp 中的“await fetch”
-
或者你可以直接从 fetch 中返回 promise 并去掉异步注解
标签: reactjs asynchronous async-await fetch