title: Async/Await in Express Middleware
body: <p>I'm having trouble understanding how to properly write middleware in Express that utilizes async/await, but doesn't leave a Promise floating in the ether after it's execution. I've read a ton of blogs and StackOverflow posts, and it seems like there is some consensus around using the following pattern in async/await middleware:</p>
  
  <pre><code>const asyncHandler = fn =&gt; (req, res, next) =&gt;
    Promise
      .resolve(fn(req, res, next))
      .catch(next)
  
  app.use(asyncHandler(async (req, res, next) =&gt; {
    req.user = await User.findUser(req.body.id);
    next();
  }));
  </code></pre>
  
  <p>I understand that this makes it possible to not have to use try..catch logic in all of your aysnc route-handlers, and that it ensures that the Promise returned by the (async (req, res, next) => {}) function is resolved, but my issue is that we are returning a Promise from the asyncHandler's Promise.resolve() call:</p>
  
  <pre><code>Promise
    .resolve(fn(req, res, next))
    .catch(next)
  </code></pre>
  
  <p>And never calling then() on this returned Promise. Is this pattern used because we aren't relying on any returned value from middleware functions? Is it OK to just return Promises and never call then() on them to get their value, since there is no meaningful value returned from middleware in Express? </p>
  
  <p>I get that async/await allows us to deal with the async code and work with the returned values easily, but in Express middleware we are left with that top-level async, which resolves to a Promise, which we then resolve with Promise.resolve(), but which still resolves to a Promise...</p>
  
  <p>Also, I understand that there are 3rd party solutions to this issue, and you could just use another framework like Koa. I just want to understand how to do this properly in Express, as I'm still relatively new to backend development with Node and want to focus solely on Express till I get the fundamentals down.</p>
  
  <p>My tentative solution has been to use async/await only in non-middleware functions, and then just call then() on the returned Promises in the actual middleware, so that I can be sure I'm not doing anything naughty, like so:</p>
  
  <pre><code>app.use((req, res, next) =&gt; {
    User.findUser(req.body.id)
      .then(user =&gt; {
        req.user = user;
        next();
      })
      .catch(next)
  });
  </code></pre>
  
  <p>Which is fine with me, but I keep see the asyncWrapper code all over the place. I'm over-thinking this right?</p>