问题
I am trying to run two hooks synchronously on Feathersjs but the "addHost" function called by the statement "hook.service.find({ query: { active: '1' } }).then(page => page.data.forEach(addHost));" in the first hook is executing after the second hook. I need that all statements in hook1 finished before starting hook2. What I am doing wrong? thanks in advance! My code is the following:
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 file
module.exports = {
/* Some code here.... */
after: {
all: [],
find: [],
get: [],
create: [hook1(), hook2()],
update: [],
patch: [hook1(), hook2()],
remove: []
},
/* Some code here.... */
};
Output:
This code is executing first
This code is executing at the end
回答1:
You don't want the hook to execute synchronously but you want the asynchronous operation to finish before continuing on. This can be done by returning a Promise as documented in the asynchronous hook API docs in your case like this:
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;
});
};
};
来源:https://stackoverflow.com/questions/45468125/how-to-run-synchronous-hooks-on-feathersjs