han
han

Reputation: 97

What does `async` mean in JavaScript when it is *not* followed by `function`?

I stumble upon this code snippet while working on fastify.

module.exports = async function (fastify, opts) {
  fastify.register(proxy, {
    upstream: 'htt‌ps://news.ycombinator.com/',
    async preHandler(request, reply) {
      if (request.query.token !== 'abc') {
        throw fastify.httpErrors.unauthorized();
      }
    },
  });
};

Looks like it calls fastify.register with two parameters and the second parameter is an object. The first field is upstream but I don't get what comes next. What is this syntax after async preHandler(request, reply)...?

Upvotes: 0

Views: 144

Answers (1)

Liam
Liam

Reputation: 29654

fastify.register seemingly has this signature: fastify.register(proxy, {});. So the second parameter is an object.

As stated in MDN and by Andreas in comments you can have an object that contains a method signature. So your object can be declared as:

{
   upstream: string,
   preHandler(request, reply){}
}

Where preHandler(request, reply){} is essentially a shorthand for preHandler: function(request, reply){}

You can then declare this method signature async (again as stated in docs). Which results in:

{
   async preHandler(request, reply){}
}

The above could also be declared as:

{
   preHandler: async function(request, reply){}
}

Upvotes: 2

Related Questions