【问题标题】:How to use nested asychronous code correctly?如何正确使用嵌套的异步代码?
【发布时间】:2019-03-12 22:54:57
【问题描述】:

我使用 micro 创建了一个小 api。

运行localhost:3000/get-status 应该返回数据对象。 到目前为止,console.log() 正在打印预期的对象。

但在浏览器上我得到Endpoint not found 而在服务器上我得到错误Si7021 reset failed: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我的 getStatus() 函数做错了什么?我想我已经把一些东西与承诺和异步的东西混为一谈了。也许我不必要地嵌套了函数......

const { send } = require('micro')
const { router, get } = require('microrouter')
const Si7021 = require('si7021-sensor')

const getStatus = async (req, res) => {
  const si7021 = new Si7021({ i2cBusNo: 1 })
  const readSensorData = async () => {
    const data = await si7021.readSensorData()
    console.log(data)
    send(res, 201, { data })
  }

  si7021.reset()
    .then((result) => readSensorData())
    .catch((err) => console.error(`Si7021 reset failed: ${err} `))
}

const notFound = (req, res) => {
  console.log('NOT FOUND.')
  send(res, 404, 'Endpoint not found')
}

module.exports = router(
  get('/get-status', getStatus),
  get('/*', notFound)
)

【问题讨论】:

    标签: javascript node.js asynchronous micro


    【解决方案1】:

    看起来你的处理程序返回了一个立即解决的承诺。你能试着像这样重写最后一行吗?

    return si7021.reset()
        .then((result) => readSensorData())
        .catch((err) => console.error(`Si7021 reset failed: ${err}`));
    

    可以更简洁地写成:

    const getStatus = async (req, res) => {
      try {
        const si7021 = new Si7021({ i2cBusNo: 1 });
        await si7021.reset();
        const data = await si7021.readSensorData();
        console.log(data);
        return send(res, 201, { data });
      } catch (e) {
        console.error(`Si7021 reset failed: ${err}`)
      }
    }
    

    但您可能还想在 catch 处理程序中发送一些东西。

    另外,请注意,承诺返回自

    si7021.reset()
        .then((result) => readSensorData());
    

    不仅在.reset 失败时拒绝。它还拒绝 readSensorData 失败。所以你的错误信息不完整。总而言之,我宁愿推荐以下内容:

    const getStatus = async (req, res) => {
      try {
        const si7021 = new Si7021({ i2cBusNo: 1 });
        await si7021.reset();
        const data = await si7021.readSensorData();
        console.log(data);
        send(res, 201, { data });
      } catch (e) {
        console.error(`Si7021 failed: ${err.message}`);
        send(res, 500, err.message);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 2016-03-02
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      相关资源
      最近更新 更多