Fastify 给了我一个错误,我找不到我用 undefined 履行承诺的地方

Fastify is giving me an error I cannot find where im fulfilling a promise with undefined

提问人:whyAmIStillWorking 提问时间:11/1/2023 更新时间:11/1/2023 访问量:32

问:

我在一个简单的 Fastify 项目上设置了一个 SSE 端点。这是端点:

  app.get('/sse', async (_, res) => {
    res.raw.setHeader('Content-Type', 'text/event-stream')
    res.raw.setHeader('Cache-Control', 'no-cache')
    res.raw.setHeader('Connection', 'keep-alive')

    const updatesHashMap = {}

    const sendUpdate = async (_) => {
      const devices = await Device.getAll()
      const updates = await Update.updateData()
      console.log(new Date())

      for (const update of updates) {
        if (devices.some(device => device.id === update.deviceId)) {
          updatesHashMap[update.deviceId] = { ...update, online: !hasAMinutePassed(update.createdAt) }
        }
      }
      return res.raw.write(`data: ${JSON.stringify(updatesHashMap)}\n\n`)
    }

    const intervalId = setInterval(() => {
      sendUpdate({
        title: 'Devices',
        devices: updatesHashMap
      })
    }, 1000)

    res.raw.on('close', () => {
      clearInterval(intervalId)
    })
  })

  done()
}

在前端,我有这个连接逻辑,有一个订阅者发生

<script>
  let eventSource;

  function connectToSSE() {
    eventSource = new EventSource('/sse');

    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);

      for (const device in data) {
        document.getElementById(`free-mem-${device}`).innerText = `${data[device].freeMem}Mb`;
        document.getElementById(`online-status-${device}`).innerText = `${data[device].online ? "Online" : "Offline" }`;
        document.getElementById(`load-${device}`).innerText = `${data[device]?.load}%`;
        document.getElementById(`uptime-${device}`).innerText = `${data[device]?.uptime}m`;
        document.getElementById(`updated-at-${device}`).innerText = data[device].createdAt;
      }
    };

    eventSource.onerror = (error) => {
      console.error('SSE Error:', error);
    };
  }

  connectToSSE();

  setInterval(() => {
    eventSource.close();
    connectToSSE();
  }, 5000);

</script>

每 5 秒,我在日志中收到一个错误,如下所示:

{"level":50,"time":1698804029401,"pid":159,"hostname":"82b3f69fc8b4","reqId":"req-3c","err":{"type":"FastifyError","message":"Promise may not be fulfilled with 'undefined' when statusCode is not 204","stack":"FastifyError: Promise may not be fulfilled with 'undefined' when statusCode is not 204\n    at /app/node_modules/fastify/lib/wrapThenable.js:30:30\n    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)","name":"FastifyError","code":"FST_ERR_PROMISE_NOT_FULFILLED","statusCode":500},"msg":"Promise may not be fulfilled with 'undefined' when statusCode is not 204"}

现在,我发现该错误与客户端与后端断开连接有关,但我找不到取消订阅过程的问题所在。

我还注意到,有时客户端只是不断开连接。

这一切都发生在同一个 Fastify 应用程序中,我从应用程序内为前端提供 .eta 文件。

我已经尝试了很多关于异步方法的事情,并试图不留下没有返回语句的代码块,但到目前为止,我无法抓住问题所在。

JavaScript 节点 .js 异步 服务器发送事件 fastify

评论

0赞 Manuel Spigolon 11/1/2023
这是一个工作示例 twitter.com/ManuEomm/status/...

答: 暂无答案