JavaScript 异步编程:Promise 与 async/await 深度解析

异步编程深度解析

JavaScript 是单线程语言,异步编程是其灵魂所在。

一、从回调到 Promise

回调函数是异步编程的基石,但多层嵌套会形成"回调地狱"。

// 回调地狱
getData(function (a) {
  getMore(a, function (b) {
    getMore(b, function (c) {
      console.log(c);
    });
  });
});

二、Promise 登场

Promise 提供了链式调用的能力,让异步代码更可读。

getData()
  .then(getMore)
  .then(getMore)
  .catch(console.error);

三、async/await

async/await 让异步代码写起来像同步代码一样自然。

async function main() {
  try {
    const a = await getData();
    const b = await getMore(a);
    const c = await getMore(b);
    console.log(c);
  } catch (e) {
    console.error(e);
  }
}

四、并发控制

Promise.all 并行执行多个任务,Promise.allSettled 忽略失败继续等待。

评论(23)