首页 > 解决方案 > 从外部异步函数发送快速响应

问题描述

setTimeout在 express 路由之外有一个函数(类似于,异步工作)。在我的例子中,它是一个监听来自 SocketIO 的事件的函数。是否可以从它发送响应?

setTimeout(() => {
 res.send('Got it');
}, 1000)

app.get('/endpoint', (req, res) => {
   // wait for event 'res' from setTimout
});

标签: javascriptnode.jsexpressasynchronous

解决方案


如果您只想从另一个函数发送响应,您可以将其传递res给它以发送响应。

如果您需要在路由中做更多工作,但只有在其他函数发送响应之后(为什么?),那么您可以将其更改为返回一个 Promise:

const someFunction = res =>
  new Promise((resolve) => {
    setTimeout(() => {
      res.send('Got it');
      resolve();
    }, 1000);
  });

app.get('/endpoint', async (req, res) => {
  await someFunction(res);
  console.log('this will only be called after res sent');
});

推荐阅读