在这一点上,我有一个问题,即什么是“回调函数”,它与“高阶函数”有何不同,并且它如何与“回调队列”的概念相关?
来自 MDN:回调函数 回调函数是作为参数传递给另一个函数的函数,然后在外部函数内被调用以完成某种例行程序或操作。
看起来这个定义与高阶函数的定义有重叠。高阶函数是指传递(稍后调用)到另一个函数中的函数。
这是 MDN 回调函数示例:
如果是这样,那么为什么当我们将函数传递到其他函数中时,要将它们称为回调(而不是简单的高阶函数),当它们与回调队列和异步世界毫无关系时?
来自 MDN:回调函数 回调函数是作为参数传递给另一个函数的函数,然后在外部函数内被调用以完成某种例行程序或操作。
看起来这个定义与高阶函数的定义有重叠。高阶函数是指传递(稍后调用)到另一个函数中的函数。
这是 MDN 回调函数示例:
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
毫无疑问。
接下来我面对了 事件循环(Event Loop) 和 回调队列(Callback queue) 的概念。
console.log("me first");
setTimeout(function asyncLog() {
console.log("i am the last")
}, 2000);
console.log("me second")
Turns out the setTimeout
function is a JavaScript wrapper that interfaces with the Web Browser API (timer) under the hood. When called, it passes a function (asyncLog
) and a timer value (2000ms) to the Timer API. After the timer completes its work, it sends the asyncLog
function to the callback queue in the web browser. This function will be invoked in the call stack as soon as the JS call stack is empty and has processed everything in the global execution context. Finally, after the last line of code (console.log("me second")
) is processed, the Event Loop passes the asyncLog
function from the callback queue to the call stack and executes it. The final order is:me first
me second
i am the last
在第一个例子中,尽管我们将greeting
称为“回调”函数,但我的理解表明整个“回调队列”机制完全被跳过了:我们没有进行任何异步操作,也没有与Web浏览器API进行交互(一切都被封装在JS中)。如果是这样,那么为什么当我们将函数传递到其他函数中时,要将它们称为回调(而不是简单的高阶函数),当它们与回调队列和异步世界毫无关系时?