【问题标题】:Send express response from outside asynchronous function从外部异步函数发送快速响应
【发布时间】:2018-04-29 16:13:11
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript node.js express asynchronous


    【解决方案1】:

    如果您只是想从另一个函数发送响应,您可以将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');
    });
    

    【讨论】:

    • 我认为这在我的实际情况下不起作用。你能在这里检查我的问题吗:stackoverflow.com/questions/50087400/…
    • 你可以传递res作为你的发射数据,然后让io.on中的代码发回响应。
    • 我没明白。可以把它作为答案在那里
    • 我试过了:io.emit('req', {data: test, res: res});但是给我一个最大调用堆栈大小超出
    • 添加日志以查看哪个函数被递归调用。
    猜你喜欢
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 2017-09-14
    • 2017-07-03
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    相关资源
    最近更新 更多