同步 vs 异步 🔄

JavaScript 是单线程语言,同步代码会按顺序执行,阻塞后续操作:

console.log('Start');  
console.log('End');  
// 输出顺序:Start → End  

异步代码通过事件循环实现非阻塞:

JavaScript_Event_Loop
📌 异步编程的核心是**回调函数**,但现代开发更推荐使用 `Promise` 和 `async/await`。

Promise 对象 🧩

  • 状态:Pending → Fulfilled/Rejected
  • 链式调用.then().catch().finally()
  • 静态方法Promise.resolve(), Promise.reject(), Promise.all()
Promise_State_Transition
🔗 [了解更多 Promise 使用技巧](/learn/resources/javascript-promises)

async/await 语法 ✅

async function fetchData() {  
  try {  
    const response = await fetch('https://api.example.com/data');  
    return await response.json();  
  } catch (error) {  
    console.error('请求出错:', error);  
  }  
}  
  • 简化回调地狱
  • 支持 await 的函数必须为 async
  • try/catch 配合处理错误

实际应用 📈

  • 网络请求:使用 fetchaxios
  • 定时任务setTimeout, setInterval
  • DOM 操作:事件监听与回调
Async_Function_Example

🔗 探索更深入的异步编程实践