回调
一句话解释
回调是 函数通过到 another 函数 as 实参, 到是 called later 当某事 happens.
用大白话说
A callback is a function you hand to another function and say "call 这个当你是做." The receiving function calls your callback at the right moment — after a computation finishes, after data loads, or when an event occurs.
Callbacks are everywhere in JavaScript because the language is event-driven and asynchronous. For example, addEventListener('点击', 回调) calls 回调 every time the user clicks. setTimeout(回调, 1000) calls 回调 after one second.
When callbacks themselves trigger more callbacks, you can end up with deeply nested code known as "回调 hell." Promises and async/await were introduced to make asynchronous code easier to read and write, but callbacks remain a fundamental pattern.
示例
function greet(name, callback) {
const message = "Hello, " + name;
callback(message);
}
greet("Ada", (msg) => {
console.log(msg); // "Hello, Ada"
});greet takes 回调 as 它的其次实参 and calls 它使用 generated 消息.
常见混淆
容易混淆的对象: Promise
关键区别: 回调是 函数通过到 是 called later; Promise 是对象 representing future 值. Promise 是 composable and avoid 回调 hell, 虽然回调是 simpler 但 harder 到链.
相关术语
相关资源
相关课程
- 函数
回调是 函数通过 as 实参
- 异步 JavaScript
回调, Promise, and 异步/等待
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。