如何正确使用嵌套异步代码?

How to use nested asychronous code correctly?

我用 microapi 创造了一点。

运行 localhost:3000/get-status 应该 return 数据对象。 到目前为止,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)
)

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

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 处理程序中发送一些内容。

此外,请注意,

返回的 promise
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);
  }
}