FeathersJS - 在哪里链接钩子?
FeathersJS - Where to chain hooks?
我有一个函数可以完成三个不同的任务,效果很好。为了更好的可重用性,我尝试将它们分成三个独立的挂钩。
它们看起来像这样:
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);
};
};
我的 service.hook 文件包含这个:
module.exports = {
before: {
find: [ firstHook(), secondHook(), thirdHook() ]}}
现在它们似乎同时 运行,这导致第三个抛出错误,这是由于第一个和第二个缺少数据引起的。我要他们一个接一个运行。我怎样才能做到这一点?
(我试图在 service.hook
中使用 .then
但它抛出 TypeError: hookFunction(...).then is not a function
。)
我读过 但我不太清楚 在哪里放置链接 - 在第三个挂钩或服务挂钩或其他地方?
挂钩将 运行 按照它们注册的顺序进行,如果它们 return 一个承诺(或者是一个 async
函数),它将等待该承诺解决。如果他们一次 运行 但应该按顺序 运行 最常见的错误是没有承诺或错误的承诺正在 returned 但如果是这样的话,从你的代码示例中不清楚案子。下面的示例将工作并等待一秒钟,然后打印当前名称并移动到下一个:
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') ]}}
我有一个函数可以完成三个不同的任务,效果很好。为了更好的可重用性,我尝试将它们分成三个独立的挂钩。 它们看起来像这样:
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);
};
};
我的 service.hook 文件包含这个:
module.exports = {
before: {
find: [ firstHook(), secondHook(), thirdHook() ]}}
现在它们似乎同时 运行,这导致第三个抛出错误,这是由于第一个和第二个缺少数据引起的。我要他们一个接一个运行。我怎样才能做到这一点?
(我试图在 service.hook
中使用 .then
但它抛出 TypeError: hookFunction(...).then is not a function
。)
我读过
挂钩将 运行 按照它们注册的顺序进行,如果它们 return 一个承诺(或者是一个 async
函数),它将等待该承诺解决。如果他们一次 运行 但应该按顺序 运行 最常见的错误是没有承诺或错误的承诺正在 returned 但如果是这样的话,从你的代码示例中不清楚案子。下面的示例将工作并等待一秒钟,然后打印当前名称并移动到下一个:
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') ]}}