Feathers: Example of async/await for hooks needed

Created on 24 Sep 2017  ·  4Comments  ·  Source: feathersjs/feathers

It would be really great if someone could give a working example of a hook function that is using ES7 async/await pattern.

The generator generates a stub like this:

// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html

module.exports = function (options = {}) { // eslint-disable-line no-unused-vars
  return function myHook (hook) {
    // Hooks can either return nothing or a promise
    // that resolves with the `hook` object for asynchronous operations
    return Promise.resolve(hook);
  };
};

I couldn't find a way to make an awaitable call like

response = await request('https://whatever.com')

inside the myHook. Any help is greatly appreciated!

Most helpful comment

I was thinking this morning of adding some examples though indeed.

All 4 comments

You just have to make return function myHook async:

// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html

module.exports = function (options = {}) { // eslint-disable-line no-unused-vars
  return async function myHook (hook) {
    const body = await request('https://whatever.com');
    return hook;
  };
};

I was thinking this morning of adding some examples though indeed.

Thanks a lot! After removing my stupid mistake and using your example everything works perfect! I think it's a good idea to add an example to the docs since async/await makes the code so much more readable.

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue with a link to this issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings