async/await是基于promise的语法糖,使异步代码更直观;async函数自动返回Promise,await在async内暂停执行并等待Promise完成,支持错误捕获且不阻塞线程。

async/await 是 javaScript 中处理异步操作的语法糖,本质是基于 Promise 的封装,让异步代码写起来像同步代码一样直观。 它不会改变异步的本质,但大幅简化了 Promise 链式调用和错误处理的写法。
async 函数:自动返回 Promise 的函数
在函数声明前加 async,该函数就变成异步函数。它会自动把返回值包装成 Promise:
- 如果函数返回普通值(如
return 42),实际返回的是Promise.resolve(42) - 如果函数抛出异常(
throw new Error()),等价于返回Promise.reject(...) - 如果返回一个已存在的 Promise,就直接返回它(不额外包装)
await:暂停执行,等待 Promise settle
await 只能在 async 函数内部使用。 它会让 js 引擎暂停当前 async 函数的执行,等待右侧表达式(必须是 Promise 或 thenable)完成(fulfilled 或 rejected),然后继续执行:
- 如果 Promise 成功(fulfilled),
await promise的结果就是promise.then(value => value)中的value - 如果 Promise 失败(rejected),
await会抛出错误,可以用try...catch捕获 - 注意:
await不会阻塞整个线程,只是暂停当前 async 函数;其他任务(如事件、定时器)仍可正常运行
常见用法示例
对比传统 Promise 写法与 async/await:
立即学习“Java免费学习笔记(深入)”;
// Promise 风格 fetch('/api/data') .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); // async/await 风格 async function getData() { try { const res = await fetch('/api/data'); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } }
await 处理非 Promise 值
await 会自动对非 Promise 值调用 Promise.resolve():
-
await 123等价于await Promise.resolve(123),立即得到123 -
await { then() { ... } }(thenable 对象)也会被当作 Promise 处理 - 但
await NULL、await undefined也合法,它们会被转为Promise.resolve(null)等
不复杂但容易忽略:await 后面不是 Promise 也能用,但真正有意义的等待,还是得靠真正的异步 Promise。