Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

hapi-async-handler

1.0.3 • Public • Published

hapi-async-handler Build Status

Adds support for ES7 async functions to hapi route handlers

npm package

ES7 Async Functions

ES7 introduces async functions, which are functions that support the await keyword and return promises. This hapi plugin adds a handler called async that allows you to write your route handlers using async functions. You can also use hapi-async-handler with io.js, generator functions (and the yield keyword), and co today. There are examples of both styles of use shown below.

Using hapi-async-handler

Registering the Plugin

var server = new Hapi.Server();
server.register([
  require('hapi-async-handler')
], function(error) { ... });

Defining a Route Handler

Define an async function that receives request and reply like a normal route handler and assign it the async property of the route handler.

server.route({
  method: 'GET',
  path: '/',
  handler: {
    // The "async" handler accepts an async function
    async: async function(request, reply) {
      // instapromise gives you promises from methods with Node-style callbacks
      require('instapromise');
      var fileContents = await fs.promise.readFile('example.txt', 'utf8');
      reply(fileContents);
    }
  }
});

For the async keyword to work, you will need to transform your source code with Babel, regenerator, or a similar compiler.

Using co

You can also use co and generator functions without any source-code transformations if you are using io.js.

server.route({
  method: 'GET',
  path: '/',
  handler: {
    // co.wrap creates a function that returns a promise, just like an async function
    async: co.wrap(function*(request, reply) {
      require('instapromise');
      var fileContents = yield fs.promise.readFile('example.txt', 'utf8');
      reply(fileContents);
    })
  }
});

install

npm i hapi-async-handler

Downloadsweekly downloads

314

version

1.0.3

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
  • avatar