回调可用于提供方法完成后要执行的代码:
/** * @arg {Function} then continuation callback */ function doSomething(then) { console.log('Doing something'); then(); } // 做某事,然后执行回调以记录“完成” doSomething(function () { console.log('Done'); }); console.log('Doing something else'); // 输出: // "Doing something" // "Done" // "Doing something else"
doSomething()上面的方法与回调同步执行-执行块直到doSomething()返回为止,确保在解释器继续执行之前执行回调。
回调还可以用于异步执行代码:
doSomethingAsync(then) { setTimeout(then, 1000); console.log('Doing something asynchronously'); } doSomethingAsync(function() { console.log('Done'); }); console.log('Doing something else'); // 输出: // "Doing something asynchronously" // "Doing something else" // "Done"
该then回调被认为是延续doSomething()的方法。提供回调作为函数中的最后一条指令称为尾调用,该尾调用由ES2015解释程序优化。