Gijo Varghese
Gijo Varghese

Reputation: 11780

Send express response from outside asynchronous function

There is a function (similar to setTimeout, that works asynchronously) outside the express route. In my case, it's a function that listens for events from SocketIO. Is it possible to send the response from it?

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

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

Upvotes: 0

Views: 227

Answers (1)

Roy Wang
Roy Wang

Reputation: 11260

If you just want to send the response from another function, you can just pass res to it for it to send the response.

If you need to do more work in the route, but only after the other function sends the response (why?), then you can change it to return a 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');
});

Upvotes: 1

Related Questions