首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >分拣与分拣的问题

分拣与分拣的问题
EN

Stack Overflow用户
提问于 2022-02-26 02:27:10
回答 1查看 30关注 0票数 0

目前,我正试图通过一个and循环在我的数据库中添加10个不同的值,然后用"res 200“进行响应。然而,在循环启动之前,res 200似乎已经运行,而且我一直收到错误:“在将头发送到客户端之后不能设置它们”。

我的代码:

代码语言:javascript
复制
app.post("/api/v1/getWeatherData",async(req,res)=>{
  let sources = await db.query("SELECT * FROM weather where element = 'mean(air_temperature P1D)' LIMIT 10;")
  console.log(sources.rows)
  try{
    let count = 1
    sources.rows.map(async(source)=>{
      sleep(5000)
      fetch(`https://frost.met.no/observations/v0.jsonld?sources=${source.source_id}&referencetime=${(source.valid_from).split("T")[0]}%2F2022-02-20&elements=mean(air_temperature%20P1D)&fields=value%2C%20referenceTime`, {
              method: "get",
              body: JSON.stringify(),
              headers: {
                Authorization:
                  "MYSECRET",
              },
            })
              .then((res) => res.json())
              .then(async tempData => {
                /* tempData.data.map(async (currentWeatherData)=>{
                  await db.query("INSERT INTO weather_data(weather_id,element,time,value) values ($1,'mean(air_temperature P1D)',$2,$3);",[input.rows[0].weather_id,currentWeatherData.referenceTime.split("T")[0],parseInt(currentWeatherData.observations[0].value)])
                }) */
                console.log("completed"); 
                count+=1
                console.log("happend")
    
        })
    })
if (count >=10){
    console.log(count)
    res.status(200).json({
      status: "success",
      data: {
        value: "Oppdatert",
      },
    });
  }
  }
  catch(err){console.log(err)}
})```
EN

回答 1

Stack Overflow用户

发布于 2022-02-26 02:43:15

您必须等待完成fetch()操作后,您的计数器才会有效。最简单的方法是使用await对它们进行排序,如下所示:

代码语言:javascript
复制
app.post("/api/v1/getWeatherData", async (req, res) => {
    try {
        let sources = await db.query(
            "SELECT * FROM weather where element = 'mean(air_temperature P1D)' LIMIT 10;")
        let count = 1;
        for (let source of sources.rows) {
            await sleep(5000);
            let res = await fetch(
                `https://frost.met.no/observations/v0.jsonld?sources=${source.source_id}&referencetime=${(source.valid_from).split("T")[0]}%2F2022-02-20&elements=mean(air_temperature%20P1D)&fields=value%2C%20referenceTime`, {
                    method: "get",
                    headers: {
                        Authorization: "MYSECRET",
                    },
                });
            let tempData = await res.json();
            /* tempData.data.map(async (currentWeatherData)=>{
              await db.query("INSERT INTO weather_data(weather_id,element,time,value) values ($1,'mean(air_temperature P1D)',$2,$3);",[input.rows[0].weather_id,currentWeatherData.referenceTime.split("T")[0],parseInt(currentWeatherData.observations[0].value)])
            }) */
            console.log("completed");
            count += 1
            console.log("happend")

        }
        if (count >= 10) {
            console.log(count)
            res.status(200).json({
                status: "success",
                data: {
                    value: "Oppdatert",
                },
            });
        }
    } catch (err) { 
        console.log(err);
        res.sendStatus(500);
    }
});

更改摘要:

res.json()

  • Move

  • await添加到fetch()并将await添加到fetch()以捕获所有错误,包括在await db.query()

  • Remove上从fetch()调用中添加body参数,因为GET请求不应该发送任何对象。

  • res.sendStatus(500)添加到捕获处理程序,因此总是发送某种类型的响应。显然,当出现错误时,您可以将其更改为任何适当的响应,但是您必须在response.

  • Add之前发送一些await,因为如果没有它,它实际上不会做任何事情。注意,这意味着需要50秒(5 * 10)才能将响应发送回客户端.

注:

在count不是>= 10的情况下,您可能需要一个else语句并在那里发送某种响应,因为通过这段代码的所有路径都必须发送某种类型的http响应。我不知道你想测试什么。

如果您希望并能够并行运行所有请求,您也可以通过累积承诺并使用Promise.all()来知道它们何时完成,就可以做到这一点:

代码语言:javascript
复制
app.post("/api/v1/getWeatherData", async (req, res) => {
    try {
        let sources = await db.query(
            "SELECT * FROM weather where element = 'mean(air_temperature P1D)' LIMIT 10;")
        let count = 1;
        await Promise.all(sources.rows.map(async source => {
            let res = await fetch(
                `https://frost.met.no/observations/v0.jsonld?sources=${source.source_id}&referencetime=${(source.valid_from).split("T")[0]}%2F2022-02-20&elements=mean(air_temperature%20P1D)&fields=value%2C%20referenceTime`, {
                    method: "get",
                    headers: {
                        Authorization: "MYSECRET",
                    },
                });
            let tempData = await res.json();
            /* tempData.data.map(async (currentWeatherData)=>{
              await db.query("INSERT INTO weather_data(weather_id,element,time,value) values ($1,'mean(air_temperature P1D)',$2,$3);",[input.rows[0].weather_id,currentWeatherData.referenceTime.split("T")[0],parseInt(currentWeatherData.observations[0].value)])
            }) */
            console.log("completed");
            count += 1
            console.log("happend")
        }));
        if (count >= 10) {
            console.log(count)
            res.status(200).json({
                status: "success",
                data: {
                    value: "Oppdatert",
                },
            });
        }
    } catch (err) {
        console.log(err);
        res.sendStatus(500);
    }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71273624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档