本文材料很大程度上受 Mixu 的 Node.js 一书启发。
从本质上讲,JavaScript 被设计为在“主”线程上非阻塞运行,视图正是在这里渲染的。可以想象这在浏览器中有多么重要。当主线程被阻塞时,就会导致最终用户所畏惧的臭名昭著的“卡死”,并且无法派发其他事件,例如导致数据获取丢失。
这带来了一些独特的约束,只有函数式编程风格才能应对。回调正是在这里派上用场。
然而,在更复杂的流程中,回调可能变得难以处理。这常常导致“回调地狱”:多层嵌套的带回调的函数让代码更难阅读、调试和组织。
async1(function (input, result1) { async2(function (result2) { async3(function (result3) { async4(function (result4) { async5(function (output) { // 对 output 做些处理 }); }); }); }); });
当然,在现实生活中很可能还会有额外的代码行来处理 result1、result2 等,因此,这个问题的长度和复杂性通常导致代码看起来比上面的例子混乱得多。
这正是_函数_大显身手的地方。更复杂的操作由许多函数组成:
- 启动器风格 / 输入
- 中间件
- 终止器
“启动器风格 / 输入”是序列中的第一个函数。该函数接受操作的原始输入(如果有)。操作是一系列可执行的函数,原始输入主要是:
- 全局环境中的变量
- 带参数或不带参数的直接调用
- 通过文件系统或网络请求获得的值
网络请求可以是由外部网络、同一网络中的另一个应用发起的传入请求,也可以是由应用自身向同一网络或外部网络发起的请求。
中间件函数会返回另一个函数,终止器函数会调用回调。下面演示流向网络或文件系统请求的过程。这里延迟为 0,因为所有这些值都在内存中可用。
function final(someInput, callback) { callback(`${someInput} and terminated by executing callback `); } function middleware(someInput, callback) { return final(`${someInput} touched by middleware `, callback); } function initiate() { const someInput = 'hello this is a function '; middleware(someInput, function (result) { console.log(result); // 需要通过回调来 `return` 结果 }); } initiate();
函数可能依赖于状态,也可能不依赖。当函数的输入或其他变量依赖外部函数时,就会产生状态依赖。
因此,状态管理主要有两种策略:
- 将变量直接传给函数,以及
- 从缓存、会话、文件、数据库、网络或其他外部来源获取变量值。
注意,我没有提到全局变量。用全局变量管理状态往往是一种粗糙的反模式,使状态难以甚至无法保证。在复杂程序中应尽可能避免使用全局变量。
如果对象在内存中可用,就可以进行迭代,控制流不会发生变化:
function getSong() { let _song = ''; let i = 100; for (i; i > 0; i -= 1) { _song += `${i} beers on the wall, you take one down and pass it around, ${ i - 1 } bottles of beer on the wall\n`; if (i === 1) { _song += "Hey let's get some more beer"; } } return _song; } function singSong(_song) { if (!_song) { throw new Error("song is '' empty, FEED ME A SONG!"); } console.log(_song); } const song = getSong(); // 这会正常工作 singSong(song);
然而,如果数据存在于内存之外,迭代就不再有效:
function getSong() { let _song = ''; let i = 100; for (i; i > 0; i -= 1) { setTimeout(function () { _song += `${i} beers on the wall, you take one down and pass it around, ${ i - 1 } bottles of beer on the wall\n`; if (i === 1) { _song += "Hey let's get some more beer"; } }, 0); } return _song; } function singSong(_song) { if (!_song) { throw new Error("song is '' empty, FEED ME A SONG!"); } console.log(_song); } const song = getSong('beer'); // 这不会正常工作 singSong(song); // Uncaught Error: song is '' empty, FEED ME A SONG!
为什么会这样?setTimeout 指示 CPU 把指令存放到总线上的其他位置,并指示数据在稍后某个时间再取回。在 0 毫秒标记处函数再次命中之前,已经过去了数千个 CPU 周期;此时 CPU 从总线取回指令并执行。唯一的问题是,歌曲('')在数千个周期之前就已经被返回了。
处理文件系统和网络请求时也会出现同样的情况。主线程根本无法被阻塞一段不确定的时间——因此,我们使用回调以可控的方式安排代码在适当的时候执行。
使用以下 3 种模式,你几乎可以完成所有操作:
- **串行:**函数将严格按照顺序执行,这种方式最类似于
for循环。
// 在别处定义并准备好执行的操作 const operations = [ { func: function1, args: args1 }, { func: function2, args: args2 }, { func: function3, args: args3 }, ]; function executeFunctionWithArgs(operation, callback) { // 执行函数 const { args, func } = operation; func(args, callback); } function serialProcedure(operation) { if (!operation) { process.exit(0); // 完成 } executeFunctionWithArgs(operation, function (result) { // 在回调之后继续 serialProcedure(operations.shift()); }); } serialProcedure(operations.shift());
- **限量串行:**函数将严格按照顺序执行,但对执行次数有限制。当你需要处理一个很大的列表,同时又要限制成功处理的项目数量时,这很有用。
let successCount = 0; function final() { console.log(`dispatched ${successCount} emails`); console.log('finished'); } function dispatch(recipient, callback) { // `sendMail` 是一个假想的 SMTP 客户端 sendMail( { subject: 'Dinner tonight', message: 'We have lots of cabbage on the plate. You coming?', smtp: recipient.email, }, callback ); } function sendOneMillionEmailsOnly() { getListOfTenMillionGreatEmails(function (err, bigList) { if (err) { throw err; } function serial(recipient) { if (!recipient || successCount >= 1000000) { return final(); } dispatch(recipient, function (_err) { if (!_err) { successCount += 1; } serial(bigList.pop()); }); } serial(bigList.pop()); }); } sendOneMillionEmailsOnly();
- **完全并行:**当顺序无关紧要时,例如给 1,000,000 个邮件收件人发送邮件。
let count = 0; let success = 0; const failed = []; const recipients = [ { name: 'Bart', email: 'bart@tld' }, { name: 'Marge', email: 'marge@tld' }, { name: 'Homer', email: 'homer@tld' }, { name: 'Lisa', email: 'lisa@tld' }, { name: 'Maggie', email: 'maggie@tld' }, ]; function dispatch(recipient, callback) { // `sendMail` 是一个假想的 SMTP 客户端 sendMail( { subject: 'Dinner tonight', message: 'We have lots of cabbage on the plate. You coming?', smtp: recipient.email, }, callback ); } function final(result) { console.log(`Result: ${result.count} attempts \ & ${result.success} succeeded emails`); if (result.failed.length) { console.log(`Failed to send to: \ \n${result.failed.join('\n')}\n`); } } recipients.forEach(function (recipient) { dispatch(recipient, function (err) { if (!err) { success += 1; } else { failed.push(recipient.name); } count += 1; if (count === recipients.length) { final({ count, success, failed, }); } }); });
每种模式都有自己的用例、优点和问题,你可以动手试验并阅读更多细节。最重要的是,记住要把操作模块化并使用回调!如果有任何疑问,就把所有东西都当作中间件来处理!