如何在 feathersjs 上 运行 同步挂钩

How to run synchronous hooks on feathersjs

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

挂钩 1:

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');
}

挂钩 2:

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.... */

};

输出:

这段代码先执行

这段代码执行到最后

您不希望挂钩同步执行,但希望异步操作在继续之前完成。这可以通过在您的情况下返回 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;
      });
  };
};