回调越来越成为编码中的一项要求,尤其是当您考虑Node.JS
非阻塞工作方式时。但是写很多协程回调很快就会变得难以回读。
例如,想象像这样的末日金字塔:
// This asynchronous coding style is really annoying. Anyone invented a better way yet?
// Count, remove, re-count (verify) and log.
col.count(quertFilter, function(err, countFiltered) {
col.count(queryCached, function(err, countCached) {
col.remove(query, function(err) {
col.count(queryAll, function(err, countTotal) {
util.log(util.format('MongoDB cleanup: %d filtered and %d cached records removed. %d last-minute records left.', countFiltered, countCached, countTotal));
});
});
});
});
是我们经常看到的东西,而且很容易变得更复杂。
当每个函数至少长几行时,分离函数开始变得可行:
// Imagine something more complex
function mary(data, pictures) {
// Do something drastic
}
// I want to do mary(), but I need to write how before actually starting.
function nana(callback, cbFinal) {
// Get stuff from database or something
callback(nene, cbFinal, data);
}
function nene(callback, cbFinal, data) {
// Do stuff with data
callback(nini, cbFinal, data);
}
function nini(callback, data) {
// Look up pictures of Jeff Atwood
callback(data, pictures);
}
// I start here, so this story doesn't read like a book even if it's quite straightforward.
nana(nene, mary);
但是一直有很多路过的 vars 发生。在中间编写其他函数时,这变得难以阅读。这些功能本身可能太微不足道,无法证明给他们自己的文件是合理的。