回调函数的问题

早期 JS 异步全靠回调,嵌套一多就陷入「回调地狱」:

getUser(id, function(user) {
  getPosts(user.id, function(posts) {
    getComments(posts[0].id, function(comments) {
      console.log(comments);
    });
  });
});

Promise 的改进

Promise 把嵌套改为链式:

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

async/await 的乐趣

async/await 让异步代码看起来像同步代码:

async function loadData(id) {
  try {
    const user = await getUser(id);
    const posts = await getPosts(user.id);
    const comments = await getComments(posts[0].id);
    console.log(comments);
  } catch (err) {
    console.error(err);
  }
}

总结

返回技艺录