异步编程的演进

JavaScript 异步编程经历了几个阶段:

1. 回调函数时代

最早的异步处理方式,但容易陷入"回调地狱":

1
2
3
4
5
6
7
getData(function(a) {
    getMoreData(a, function(b) {
        getMoreData(b, function(c) {
            // 回调地狱...
        });
    });
});

2. Promise 的出现

Promise 让异步代码更加优雅:

1
2
3
4
5
getData()
    .then(a => getMoreData(a))
    .then(b => getMoreData(b))
    .then(c => console.log(c))
    .catch(err => console.error(err));

3. Async/Await

最现代的异步编程方式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
async function fetchData() {
    try {
        const a = await getData();
        const b = await getMoreData(a);
        const c = await getMoreData(b);
        console.log(c);
    } catch (err) {
        console.error(err);
    }
}

最佳实践

  1. 优先使用 async/await - 代码更清晰易读
  2. 正确处理错误 - 使用 try/catch 或 .catch()
  3. 并行执行 - 使用 Promise.all() 提升性能
  4. 避免阻塞 - 合理使用异步操作

常见陷阱

  • 忘记 await 关键字
  • 在循环中使用 await
  • 错误处理不当

掌握异步编程,写出更优雅的 JavaScript 代码!