javascript如何实现异步编程_回调、Promise和Async/Await怎么用?

回调函数是基础异步方式但易致“地狱回调”,Promise通过链式调用扁平化逻辑,async/await进一步简化为同步风格;三者需注意错误处理、执行时机及转换规范。

回调函数容易导致“地狱回调”,但仍是基础

回调是最原始的异步处理方式,setTimeoutfs.readFileXMLHttpRequest 都依赖它。问题在于嵌套多层后逻辑难以维护,错误处理分散,且无法用 try/catch 捕获。

  • 回调必须作为最后一个参数传入(Node.js 风格),约定第一个参数是 err,第二个起才是数据
  • 每次调用都得手动检查 if (err) { ... },漏掉就可能静默失败
  • 多个串行异步操作会写成:回调里再调回调,再套一层,缩进越来越深
fs.readFile('a.txt', 'utf8', (err, dataA) => {
  if (err) throw err;
  fs.readFile('b.txt', 'utf8', (err, dataB) => {
    if (err) throw err;
    console.log(dataA + dataB);
  });
});

Promise 解决嵌套,但链式调用需注意 .then 的返回值

Promise 把回调“扁平化”,用 .then().catch() 统一处理成功与失败。关键点在于:.then() 中 return 的值,会成为下一个 .then() 的输入;如果 return 一个 Promise,则自动等待它 resolve 后再往下走。

  • 不要在 .then() 里直接写 console.log 就结束,否则后续 .then() 收到 undefined
  • Promise.all([p1, p2]) 并发执行,任一 reject 整体就失败;需要全部结果且允许失败,得用 Promise.allSettled
  • 构造 Promise 时,resolvereject 只能触发一次,多次调用后者会被忽略
fs.promises.readFile('a.txt', 'utf8')
  .then(dataA => fs.promises.readFile('b.txt', 'utf8'))
  .then(dataB => dataA + dataB) // 注意:这里必须 return
  .then(result => console.log(result))
  .catch(err => console.error('出错了:', err));

async/await 让异步代码看起来像同步,但 await 只对 Promise 生效

async 函数本质是返回 Promise 的语法糖,await 只能出现在 async 函数内部,且只能等待 Promisethenable 或普通值(后者会立即 resolve)。

  • 不能 await 普通回调函数,比如 await setTimeout(...) 是错的,得先包装成 Promise
  • 并发请求别傻等:用 await Promise.all([p1, p2]),而不是连续写两个 await
  • 错误必须用 try/catch 捕获,.catch() 在 async 函数外不生效
async function readBoth() {
  try {
    const [dataA, dataB] = await Promise.all([
      fs.promises.readFile('a.txt', 'utf8'),
      fs.promises.readFile('b.txt', 'utf8')
    ]);
    return dataA + dataB;
  } catch (err) {
    console.error('读取失败:', err);
  }
}

混用时要注意执行时机和错误传播路径

实际项目中经常遇到回调转 Promise、Promise 被 await、甚至 Promise.reject() 被 throw 出来。最容易被忽略的是:Promise 构造函数里的同步错误(比如 JSON.parse('invalid'))不会被外层 catch 捕获,而是在构造时抛出——除非你把它包在 try/catch 里再 reject

  • util.promisify(Node.js)把回调 API 转成 Promise 版本,比手写 new Promise 更可靠
  • async 函数里 throw new Error() 等价于 return Promise.reject(...)
  • 顶层 await(模块级)只在 ES 模块中有效,CommonJS 不支持

异步控制流真正难的不是语法,而是搞清每个操作到底在哪个微任务队列里执行、错误从哪一层冒出来、以及并发与串行的边界在哪。写完记得加日志或 debugger,光看链式结构容易误判执行顺序。