3

I just read this great SO question & answer about how doing async/await will not block a thread: Will async/await block a thread node.js

I wanted to sanity check something when doing this in the context of Express.js.

Will the following code block any process and/or will express let runAsyncMethodThatReturnsPromise complete in the background:

const myEndpoint = async(req, res) => {
  const users = await DB.getSomeUsers();
  users.forEach(user => {
    user.runAsyncMethodThatReturnsPromise();
  });

  res.send('Ok');
}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Dave Stein
  • 8,653
  • 13
  • 56
  • 104
  • 2
    You are right, `user.runAsyncMethodThatReturnsPromise();` will run in the background and will not block the event loop :) – Thom Oct 04 '19 at 14:39
  • @Thom So when I run a method in the router of express, is it basically awaiting on its own promise that resolves the second I call `res.send` and that is the only thing that blocks a thread? – Dave Stein Oct 04 '19 at 14:46
  • 1
    It really depends on how `runAsyncMethodThatReturnsPromise()` is implemented. Just because it returns a promise doesn't mean it's not a CPU-bound function. – Patrick Roberts Oct 04 '19 at 14:54
  • Yes, and I don't think that is blocking the thread. You might be mixing two different things: thread blocking and async/await. There is only a few things that might actually block the event loop/thread. You can read more about that [here](https://nodejs.org/uk/docs/guides/dont-block-the-event-loop/). – Thom Oct 04 '19 at 14:57
  • 1
    For example `runAsyncMethodThatReturnsPromise() { return new Promise(() => { for (let i = 0; i < 1e9; ++i) { } }); }` _will_ block the event loop. – Patrick Roberts Oct 04 '19 at 15:06

0 Answers0