1. async
的作用
#
在 TypeScript(以及 JavaScript)中,async
关键字用来 声明一个异步函数。
它有两个核心效果:
返回值会被自动封装为
Promise
- 即使函数中直接返回一个值,也会被包装成
Promise.resolve(value)
。
- 即使函数中直接返回一个值,也会被包装成
允许在函数内部使用
await
await
可以让异步调用看起来像同步代码,从而提升可读性。
2. 基本语法 #
async function foo(): Promise<string> {
return "hello"; // 实际返回 Promise<string>
}
foo().then(result => console.log(result)); // 输出 "hello"
等价于:
function foo(): Promise<string> {
return Promise.resolve("hello");
}
3. await
的用法
#
await
只能在 async
函数内部使用,用于等待一个 Promise
完成。
示例:
function delay(ms: number): Promise<string> {
return new Promise(resolve => setTimeout(() => resolve("done"), ms));
}
async function run() {
console.log("start");
const result = await delay(1000); // 等待 1 秒
console.log(result); // "done"
}
run();
这里 await
会 暂停函数执行,直到 delay(1000)
的 Promise
被 resolve。
4. 错误处理 #
在 async
函数中,如果 Promise
被 reject,会抛出异常,可以用 try...catch
捕获:
async function mayFail() {
throw new Error("Oops!");
}
async function main() {
try {
await mayFail();
} catch (err) {
console.error("Caught:", err);
}
}
main();
等价写法(不用 async/await
):
mayFail().catch(err => console.error("Caught:", err));
5. async
的类型推断
#
TypeScript 会根据 return
类型推断异步函数的 Promise
包裹类型:
async function f1() {
return 123;
}
// f1(): Promise<number>
async function f2() {
return "hi";
}
// f2(): Promise<string>
如果显式写返回值类型,必须是 Promise<T>
:
async function f3(): Promise<boolean> {
return true;
}
6. async
的常见场景
#
异步请求(如
fetch
)async function getData() { const res = await fetch("https://api.example.com/data"); return res.json(); }
顺序执行多个异步任务
async function process() { const a = await task1(); const b = await task2(a); return b; }
并行执行(配合
Promise.all
)async function parallel() { const [a, b] = await Promise.all([task1(), task2()]); return { a, b }; }
7. 注意事项 #
async
函数 始终返回Promise
,即使没有await
。在顶层作用域(模块最外层)中,早期不能直接用
await
,但 TypeScript 3.8+ 在esnext
模块下支持 Top-Level Await。异步代码要注意 错误处理,否则未捕获的 Promise rejection 会导致程序崩溃。