异步 JavaScript 与事件循环
了解异步编程模式、回调、Promise、async/await 以及 Node.js 事件循环。
异步 JavaScript 与事件循环 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is Asynchronous Code?
Asynchronous code lets Node start a slow task — a file read or network call — and keep running other code instead of blocking the main thread.
Sync vs. Async Explained
Think of a chef: synchronous means standing idle while water boils; asynchronous means chopping veggies meanwhile. Node cooks like the async chef.
The Callback Pattern
Callbacks are functions you pass to be run later — the classic way to handle async work. When the task finishes, your callback is invoked with the result or error.
Simple Callback in Action
setTimeout is a textbook async operation: it waits a set delay, then fires the callback you handed it.
function greet(name, callback) {
setTimeout(() => {
const message = `Hello, ${name}!`;
callback(message);
}, 1000); // Wait 1 second
}
function displayMessage(msg) {
console.log(msg);
}
greet("Coddy", displayMessage);
console.log("Waiting for greeting...");The Challenge of Callback Hell
Nesting many dependent callbacks creates Callback Hell — deeply indented, hard-to-read code where error handling and maintenance become a nightmare.
Introducing Promises
A Promise represents a value coming now, later, or never. It lives in one of three states: pending, fulfilled, or rejected.
Using Promises
Handle a Promise with .then() for success and .catch() for errors — cleaner chaining than nested callbacks.
function fetchData(shouldSucceed) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldSucceed) {
resolve("Data fetched successfully!");
} else {
reject("Failed to fetch data.");
}
}, 1000);
});
}
fetchData(true)
.then(data => console.log(data))
.catch(error => console.error(error));
fetchData(false)
.then(data => console.log(data))
.catch(error => console.error(error));Async/Await for Clarity
async/await is syntax over Promises that makes async code read like sync code. await pauses inside an async function until the Promise settles.
Async/Await in Practice
See how async/await flattens the previous example — and how a plain try...catch handles errors right inline.
function delayedMessage(msg, delay) {
return new Promise(resolve => {
setTimeout(() => resolve(msg), delay);
});
}
async function processMessages() {
try {
console.log("Starting process...");
const msg1 = await delayedMessage("First message!", 1000);
console.log(msg1);
const msg2 = await delayedMessage("Second message!", 500);
console.log(msg2);
console.log("Process finished.");
} catch (error) {
console.error("An error occurred:", error);
}
}
processMessages();The Node.js Event Loop
The Event Loop is Node's engine: when the call stack empties, it pulls queued callbacks and runs them — fueling non-blocking I/O on a single thread.
Async Concepts Check
Which of the following best describes the primary benefit of using asynchronous programming in Node.js?
Async & Event Loop Recap
Async work powers Node's reach: callbacks began it, Promises structured it, async/await cleaned it up, and the Event Loop drives it all.
常见问题解答
「异步 JavaScript 与事件循环」课时是免费的吗?
是的 — 「异步 JavaScript 与事件循环」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「异步 JavaScript 与事件循环」这节课中我会学到什么?
了解异步编程模式、回调、Promise、async/await 以及 Node.js 事件循环。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「异步 JavaScript 与事件循环」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Node.js 与 NPM 入门
- 详解 Node.js 模块系统
- 异步 JavaScript 与事件循环
- 使用文件系统与流