简体   繁体   中英

FeathersJS - Where to chain hooks?

I had a function that did three different tasks, which worked fine. For better re-usability I tried to separate them into three independent hooks. They look like this:

module.exports = function(options = {}) {
  return function hookFunction(hook) {
  //do stuff and set variables
  function(hook.params.var){ ... } // only in second and third
  hook.params.var = var;           // only in first and second
    return Promise.resolve(hook);
  };
}; 

My service.hook file contains this:

module.exports = {
  before: {
    find: [ firstHook(), secondHook(), thirdHook() ]}}

Now they seem to run simultaneously, which causes the third to throw an error caused by missing data from first and second. I want them to run one after another. How could I achieve that?

(I tried to use .then in service.hook but it throws TypeError: hookFunction(...).then is not a function .)

I've read How to run synchronous hooks on feathersjs but I don't quite know where to place the chaining - in the third hook or in the service hook or elsewhere?

Hooks will run in the order they are registered and if they return a promise (or are an async function) it will wait for that promise to resolve. The most common mistake if they run at once but should run in sequence is that no promise or the wrong promise is being returned but it is not clear from your code example if that is the case. The following example will work and wait one second each, then print the current name and move to the next:

function makeHook(name) {
  return function(context) {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log(`Running ${name}`);
        resolve(context);
      }, 1000);
    });
  }
}
module.exports = {
  before: {
    find: [ makeHook('first'), makeHook('second'), makeHook('third') ]}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM