异步 JavaScript
回调, Promise, 异步/等待, and 获取数据从 APIs 不使用 blocking.
你将学到
- 为什么 JavaScript 是单个-threaded and 什么事件循环做
- problem 使用回调 (回调 hell)
- Promise: 然后, catch, 最后, and chaining
- 异步/等待 for linear, readable 异步 code
- 获取 JSON 从 API 使用获取()
概念讲解
事件循环
JavaScript is single-threaded — it runs one task at a time. To avoid freezing the page on slow operations, the event loop pushes long-running work (network requests, timers) to the browser's background APIs and runs the callback when the result is ready.
This means async code does not run top-to-bottom. Understanding this is the key to avoiding race conditions and bugs.
Callbacks (the old way)
A callback is a function passed to be called later:
setTimeout(() => {
console.log("运行之后 1 其次");
}, 1000);
Nesting many callbacks creates callback hell — deeply indented, hard-to-read code:
getUser(id, (user) => {
getOrders(user, (orders) => {
getOrderItems(orders[0], (items) => {
// ... keeps nesting
});
});
});
Promises
A promise represents a value that will be available in the future. It can be pending, fulfilled, or 拒绝.
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("失败:", error))
.finally(() => console.log("做"));
Promises chain flatly and propagate errors to the next catch, which is much cleaner than nested callbacks.
async / await
异步/等待 (ES2017) lets you write async code that looks synchronous. An 异步 function always returns a promise, and 等待 pauses until the promise resolves:
async function loadData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("失败:", error);
}
}
This is the modern standard. Use it instead of 然后 chains whenever possible.
Fetching Data
获取() is the built-in API for making HTTP requests. It returns a promise that resolves to a 响应 object:
const res = await fetch("/api/users", {
method: "POST",
headers: { "内容-类型": "application/JSON" },
body: JSON.stringify({ name: "Ada" }),
});
if (!res.ok) throw new Error(`HTTP ${res.状态}`);
const users = await res.json();
Always check res.好的 — 获取 only rejects on network errors, not on HTTP 404 or 500.
Running Promises in Parallel
// Sequential — slow
const a = await fetchA();
const b = await fetchB();
// Parallel — faster
const [aResult, bResult] = await Promise.all([fetchA(), fetchB()]);
Promise.所有 runs promises concurrently and waits for all of them. Use it to speed up independent requests.
示例代码
// async/await with fetch and error handling
async function getUser(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const user = await response.json();
return user;
} catch (error) {
console.error("Failed to fetch user:", error.message);
return null;
}
}
// Run multiple requests in parallel
async function loadDashboard() {
const [user1, user2, user3] = await Promise.all([
getUser(1),
getUser(2),
getUser(3),
]);
const users = [user1, user2, user3].filter(Boolean);
users.forEach((u) => console.log(`${u.name} — ${u.email}`));
}
// A simple promise you can create yourself
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function countdown() {
for (let i = 3; i > 0; i--) {
console.log(i);
await delay(1000);
}
console.log("Go!");
}
loadDashboard();
countdown();
Shows 真实获取 call 使用错误 handling, Promise.所有 for parallel 请求, 创建 Promise 从 scratch (delay), and using 等待使用 timer 到构建 countdown.
动手试一试
- HTTP 请求 Tester
发送 GET/POST 请求 and inspect 响应 — 精确地什么获取做.
- WebSocket 客户端 Tester
异步 communication over WebSocket — another 异步模式.
常见错误
错误写法
Forgetting 等待 and 获取 Promise 对象相反的 值
正确做法
等待 pauses 直到 Promise resolves. 不使用它, 你获取 Promise 对象它自己. 总是 use 等待内部异步函数当 你需要 resolved 值.
错误写法
不检查响应.好的之后获取
正确做法
获取仅 拒绝 on network 错误. HTTP 404 or 500 still resolve. 总是检查如果 (!响应.好的) throw 新错误(...) 之前 calling 响应.JSON().
相关资源
相关工具
- 服务器-发送事件 Tester
Another 异步 streaming 模式 used in modern web apps.
- HTTP 状态 Codes
引用 for 状态 codes 你的获取 calls 将返回.
相关速查表
- JavaScript Cheatsheet
Promise, 异步/等待, and 获取引用.
练习 异步 JavaScript
15 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。