Javascript中的链接回调可读性? [英] Chained callback readability in Javascript?
问题描述
编写一系列深层嵌套回调的最好方法是什么?
What's the best way to write a series of deeply nested callbacks?
你有几个函数,每个函数执行一个异步操作,输出。对于两个函数,这通常看起来像 foo(bar)
。
You have several functions, each of which performs an asynchronous operation and which depends on the prior function's output. For two functions, this typically looks like foo(bar)
.
一系列长回调将看起来像 foo(bar(baz(qux(...))))
。这很快变得很难阅读,更不用说维护。特别是一旦你开始传递附加参数到函数调用! 步骤有所改进,但为每个函数调用添加了一个额外的参数。
A long series of callbacks will look like foo(bar(baz(qux(...))))
. This quickly becomes very difficult to read, let alone maintain. Especially once you begin passing additional parameters to the function calls! Step improves on this a bit, but adds an extra parameter to each function call.
这个post(第3.1节)建议使用一个等待函数,如下所示: wait(foo,qux)
并支持多个依赖关系,如: wait([foo,bar,baz],qux)
。不幸的是,这不会帮助嵌套回调。
This post (section 3.1) suggests a wait function, which is used like this: wait(foo, qux)
and supports multiple dependencies like so: wait([foo, bar, baz], qux)
. Unfortunately, this won't help for nested callbacks.
步骤等待两个帮助有点,但似乎都不理想。有没有更好的方式来编写长回调链?
Step and wait both help a bit, but neither seems ideal. Is there a better way to write long callback chains?
推荐答案
在函数编程中有函数调用compose,两个函数 fog = f(g(x))
In functional programming there is function call compose which create new function composition from two function f o g = f(g(x))
function compose(f, g) {
return function() {
//apply is use to pass multiple arguments to function g
return f(g.apply(null, Array.prototype.slice.call(arguments, 0)));
};
}
并且如果函数式编程范式还有函数reduce函数。
and if you have reduce function also from functional programming paradigm.
// this function need at least 2 arguments and it don't check if you pass
// one element array or empty array.
function reduce(fun, array) {
var result = fun(array[0], array[1]);
for (var i=2; i<array.length; ++i) {
result = fun(result, array[i]);
}
return result;
}
您可以使用上述两种方式创建链接函数
you can create chain function using the two above
function chain() {
return reduce(compose, arguments);
}
您可以使用chain创建一个新函数, / p>
and you can use chain to create new function which is a chain of functions
var quux = chain(foo, bar, baz);//quux is function that call foo(bar(baz(...)));
您还可以将此作为回调传递给另一个函数作为参数
you can also pass this to the other function as argument as a callback
some_function(chain(foo, bar, baz, quux));
在这种情况下,some_function将回调函数作为参数。
in this case some_function get callback function as argument.
这篇关于Javascript中的链接回调可读性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!