返回博客
JavaScript 异步编程模式

JavaScript 异步编程模式

JavaScript 的异步编程经历了从回调到 Promise 再到 async/await 的演进。

回调函数

最早的异步处理方式:

fs.readFile("file.txt", (err, data) => {
  if (err) throw err;
  console.log(data);
});

Promise

Promise 提供了更优雅的异步处理:

fetch("/api/data")
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((err) => console.error(err));

async/await

基于 Promise 的语法糖,让异步代码看起来像同步代码:

async function getData() {
  try {
    const res = await fetch("/api/data");
    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err);
  }
}