JS async/await - why does await need async?

Viewed 2054

Why does using await need its outer function to be declared async?

For example, why does this mongoose statement need the function it's in to return a promise?

async function middleware(hostname, done) {
  try {
    let team = await Teams.findOne({ hostnames: hostname.toLowerCase() }).exec();
    done(null, team);
  } catch (err) { done(err); }
}

I see the runtime/transpiler resolving the Teams promise to it's value and async signaling it "throws" rejected promises.

But try/catch "catches" those rejected promises, so why are async and await so tightly coupled?

3 Answers

Because using await inside middleware function means the middleware function can't return a result immediately (it must wait until await is settled) and middleware function callers must wait until the promise (returned from middleware function) is settled.

Related