简体   繁体   English

从自身传递回调函数作为参数

[英]Passing the callback function as parameter from itself

Is it possible for me to pass a callback parameter to another method from within the callback function block itself? 我是否可以从回调功能块本身内部将回调参数传递给另一个方法? Example: 例:

var resultCallback = function(result){
   if(result)
   {
       alert('success!');
   }else{
       callServiceB(resultCallback );
   }
}

callServiceA(resultCallback);

The reason of this is i wish to workout something like a Chain of Responsibility patterns in javascript. 这是因为我希望锻炼诸如javascript中的责任链模式之类的东西。

Tried googled but so far gets nothing. 尝试谷歌,但到目前为止什么也没有。 Any idea or comment is welcomed. 欢迎任何想法或评论。

Is it possible for me to pass a callback parameter to another method from within the callback function block itself? 我是否可以从回调功能块本身内部将回调参数传递给另一个方法?

Yes you can. 是的你可以。 Try it! 试试吧!

I wish to workout something like a Chain of Responsibility patterns 我希望锻炼诸如“责任链”模式

Putting both the responsibility chain ( callServiceB(resultCallback) ) and the resulting action ( alert('success!') ) in the same function looks like a bad practise/design smell. 将责任链( callServiceB(resultCallback) )和产生的动作( alert('success!') )放在同一函数中,似乎是一种不好的做法/设计气味。 You should use an extra callback for the result, and separate the declaration of the chain from that. 您应该对结果使用额外的回调,并从中分离的声明。

It might then look like callServiceA(orCallServiceB(alertResult)) or either(callServiceA, callServiceB, …)(alertResult) . 然后可能看起来像callServiceA(orCallServiceB(alertResult))either(callServiceA, callServiceB, …)(alertResult)

The logic is like 1. call function a 2. if function a ok, then call function b 3. if function b ok, then call function c, and so on.. – ipohfly 8 mins ago 逻辑类似于1.调用函数a 2.如果函数a正常,然后调用函数b 3.如果函数b ok,然后调用函数c,依此类推.. – ipohfly 8分钟前

That doesn't sound like a chain of responsibility , where you call the next function only if the current one failed (couldn't process the arguments)? 这听起来不像是一条责任链,只有在当前函数失败(无法处理参数)的情况下,您才调用下一个函数? What you describe sounds more like monadic chaining (one action relying on the previous one) - take a look at promises for that: 您所描述的听起来更像是单子链(一个动作依赖于前一个动作)-看一下对此的承诺

 callServiceA.then(callServiceB).then(…).then(resultCallback);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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