第43关:终极语法糖 Async/Await 🍬

XP: 0/100
🦸‍♂️

JS队长

Promise 已经很棒了,但 .then() 链还是有点啰嗦。

是时候祭出终极武器了 —— Async/Await!它让异步代码写起来像同步代码一样丝滑!✨

🐛

Bug捣蛋鬼

嘿嘿,不管你怎么变,我都会在异步的缝隙里捣乱!

🦸‍♂️

JS队长

没门!async 函数返回一个 Promise,而 await 会暂停代码执行,直到 Promise 解决。

这意味着我们可以用 try/catch 来捕获异步错误,就像处理普通错误一样!🛡️

📖 进化史:

// 1. 回调地狱 (Callback Hell) 😱
getData(function(a) {
    getMore(a, function(b) {
        console.log(b);
    });
});

// 2. Promise 链 (Promise Chain) 🙂
getData()
    .then(a => getMore(a))
    .then(b => console.log(b));

// 3. Async/Await (The Boss) 😎
async function doIt() {
    const a = await getData();
    const b = await getMore(a);
    console.log(b);
}
            

🎮 挑战:模拟数据获取任务

点击按钮,观察 async/await 如何一步步执行任务。

1. 🔍 正在查找用户信息... (await findUser)
2. 📦 正在下载用户数据... (await downloadData)
3. ✅ 处理完成!显示结果。