如何在feathersjs上运行同步钩子

时间:2017-08-02 18:11:28

标签: feathersjs

我试图在Feathersjs上同步运行两个钩子,但是“hook.service.find({query:{active:'1'}}}语句调用”addHost“函数。然后(page => page .data.forEach(addHost));”在第一个钩子中,在第二个钩子之后执行。我需要在启动hook2之前完成hook1中的所有语句。我做错了什么?提前致谢! 我的代码如下:

Hook1:

module.exports = function (options = {}) {
  return function hook1 (hook) {
    hook.service.find({ query: { active: '1' } }).then(page => page.data.forEach(addHost));
  };
};

function addHost(client) {
  /* Some code here.... */
  console.log('This code is executing at the end');
}

HOOK2:

module.exports = function (options = {}) {
  return function hook2 (hook) {
    /* Some code here.... */
    console.log('This code is executing first');
  };
};

xxx.hooks.js文件

module.exports = {
  /* Some code here.... */

  after: {
    all: [],
    find: [],
    get: [],
    create: [hook1(), hook2()],
    update: [],
    patch: [hook1(), hook2()],
    remove: []
  },

  /* Some code here.... */

};

输出:

此代码首先执行

此代码在最后执行

1 个答案:

答案 0 :(得分:1)

您不希望钩子同步执行,但您希望在继续之前完成异步操作。这可以通过在您的案例中返回Promise as documented in the asynchronous hook API docs来完成:

module.exports = function (options = {}) {
  return function hook1 (hook) {
    return hook.service.find({ query: { active: '1' } })
      .then(page => page.data.forEach(addHost))
      .then(() => {
        // Always return the `hook` object or `undefined`
        return hook;
      });
  };
};