异步代码在现代开发中无处不在。学习 `async/await` 如何让你的代码读起来像自然英语故事,而不是层层嵌套的回调地狱。

Asynchronous code is everywhere in modern development. Learn how `async/await` makes your code read like a natural English story instead of a pyramid of callbacks.

📖代码精读

// Without async/await — hard to follow the story
fetchUser(userId)
.then(user => fetchPosts(user.id))
.then(posts => filterPublished(posts))
.catch(error => console.error(error));
 
// With async/await — reads like English sentences:
async function loadUserDashboard(userId: string): Promise<Dashboard> {
try {
const user = await fetchUser(userId); // wait for user
const posts = await fetchPosts(user.id); // then wait for posts
const published = filterPublished(posts); // synchronous filter
 
return { user, posts: published }; // return the result
} catch (error) {
// Handle failure gracefully
throw new Error(`Failed to load dashboard: ${error}`);
}
}
 
// 📖 Read it aloud: 'Get the user, then get their posts,
// filter the published ones, and return all of it.'

💡 建议:把每一行代码大声用英文念出来,注释就是你的翻译。

📚单词讲解

asynchronous
/eɪˈsɪŋkrənəs/
adjective
异步的(不在同一时间发生)
await
/əˈweɪt/
verb / keyword
等待(暂停执行直到 Promise 完成)
gracefully
/ˈɡreɪsfəli/
adverb
优雅地,从容地
resolve
/rɪˈzɒlv/
verb
解析,完成(Promise 成功时)

🧠理解检验

先在脑子里想一想——再点开看参考答案。

Q1: Why is the `async/await` version easier to read than the `.then()` chain?
Q2: What does `Promise<Dashboard>` as a return type tell you?
💡核心要点▼ 展开