前端

JavaScript 异步编程演进史:从回调到 async/await

回调时代

早期的异步全靠回调函数,嵌套多了就成了"回调地狱":

getUser(id, (user) => {
  getPosts(user, (posts) => {
    getComments(posts[0], (comments) => {
      console.log(comments); // 越陷越深……
    });
  });
});

Promise 的救赎

Promise 把嵌套拍平成链式调用,错误处理也集中了:

getUser(id)
  .then(getPosts)
  .then((posts) => getComments(posts[0]))
  .catch(console.error);

async/await:像同步一样写异步

async function main() {
  const user = await getUser(id);
  const posts = await getPosts(user);
  const comments = await getComments(posts[0]);
}

async/await 只是 Promise 的语法糖,但可读性的提升是质变。

总结

  • 回调:简单但难以维护
  • Promise:链式、可组合
  • async/await:同步的外表,异步的内核