【问题标题】:Await dosent wait?等待不等待?
【发布时间】: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


【解决方案1】:

Await/async 或 Promise 具有相同的目的,您是在混合概念。

您要么创建一个 fetch 确实执行的承诺,然后使用公开的方法 Then/Catch:

fetch(...)
.then(response => response.json())
.then(success => your success code here)
.catch(error => error code here)

或者你可以像这样使用异步等待:

async function fetchTemp() {
  const response = await fetch(url);
  const json = await response.json();
  ...
}

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 2018-05-04
    • 2020-05-09
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2016-07-07
    • 2016-03-25
    相关资源
    最近更新 更多