Promise语法糖async和await的讲解


🔁 什么是 Promise?

Promise异步操作的一种解决方案,比如请求接口、定时器等。

  • 它代表一个“未来才会完成的事儿”。

  • 状态:pendingfulfilledrejected


⏳ async/await 是干嘛的?

async/await 是对 Promise语法糖,让异步写起来像同步,更清晰好读。


📦 基本结构

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("🍕 数据来啦!");
    }, 1000);
  });
}

✅ 使用 async/await 的例子

async function getData() {
  try {
    const result = await fetchData(); // 等待 Promise 完成
    console.log("结果是:", result);
  } catch (err) {
    console.log("❌ 出错了", err);
  }
}
getData();

🔍 async 函数特点

特点 说明
🔹 async 前缀 标记函数里可以用 await
🔹 自动返回 Promise async function() 默认返回一个 Promise
🔹 可以配合 try/catch 用来优雅处理错误

🚨 注意事项

⚠️ 细节 说明
await 只能用在 async 函数中  
❗ 多个 await 会一个个顺序执行(性能可能差)  
✅ 可以用 Promise.all 并行执行  

🚀 对比传统写法

✅ 使用 Promise.then

fetchData().then(res => {
  console.log(res);
}).catch(err => {
  console.log("出错了", err);
});

✅ 使用 async/await

try {
  const res = await fetchData();
  console.log(res);
} catch (err) {
  console.log("出错了", err);
}

🧠 总结一句话:

async/await 让你写异步代码像写同步一样顺畅,但本质还是基于 Promise


教育底层逻辑为何是分层和驯化

社会不会告诉普通人的秘密 · 全面系统版

评 论
请登录后再评论