Promise 已经很棒了,但 .then() 链还是有点啰嗦。
是时候祭出终极武器了 —— Async/Await!它让异步代码写起来像同步代码一样丝滑!✨
嘿嘿,不管你怎么变,我都会在异步的缝隙里捣乱!
没门!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 如何一步步执行任务。