TypeScript async/await
介绍
在现代 JavaScript 和 TypeScript 中,异步编程是处理耗时操作(如网络请求、文件读写等)的核心方式。传统的回调函数和 Promise 虽然有效,但代码可读性和维护性较差。为了解决这些问题,ES2017 引入了 async/await
语法,它让异步代码看起来更像同步代码,极大地简化了异步编程。
在 TypeScript 中,async/await
是基于 Promise 的语法糖,允许你以更直观的方式编写异步代码。本文将带你从基础到实际应用,全面掌握 async/await
。
什么是 async/await?
async/await
是 JavaScript 和 TypeScript 中处理异步操作的一种语法。它由两个关键字组成:
async
:用于声明一个异步函数。异步函数会自动返回一个 Promise 对象。await
:用于等待一个 Promise 完成,并返回其解析值。await
只能在async
函数中使用。
基本语法
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
在上面的代码中,fetchData
是一个异步函数。await
关键字会暂停函数的执行,直到 fetch
和 response.json()
的 Promise 完成。
await
只能在 async
函数中使用。如果在普通函数中使用 await
,TypeScript 会报错。
逐步讲解
1. 声明异步函数
使用 async
关键字声明一个异步函数:
async function myAsyncFunction() {
// 异步操作
}
2. 使用 await
等待 Promise
在异步函数中,可以使用 await
等待一个 Promise 完成:
async function fetchUser() {
const response = await fetch('https://api.example.com/user');
const user = await response.json();
return user;
}
3. 处理错误
使用 try/catch
捕获异步操作中的错误:
async function fetchUser() {
try {
const response = await fetch('https://api.example.com/user');
const user = await response.json();
return user;
} catch (error) {
console.error('Error fetching user:', error);
}
}
如果不使用 try/catch
,未捕获的 Promise 错误可能会导致程序崩溃。
4. 并行执行多个异步操作
如果需要并行执行多个异步操作,可以使用 Promise.all
:
async function fetchMultipleData() {
const [user, posts] = await Promise.all([
fetch('https://api.example.com/user').then(res => res.json()),
fetch('https://api.example.com/posts').then(res => res.json())
]);
return { user, posts };
}
实际案例
案例 1:获取天气数据
假设我们需要从一个天气 API 获取当前天气数据,并将其显示在页面上:
async function getWeather(city: string) {
try {
const response = await fetch(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${city}`);
const weatherData = await response.json();
console.log(`Current temperature in ${city}: ${weatherData.current.temp_c}°C`);
} catch (error) {
console.error('Error fetching weather data:', error);
}
}
getWeather('Beijing');
案例 2:批量处理文件
假设我们需要读取多个文件并处理它们的内容:
import fs from 'fs/promises';
async function processFiles(filePaths: string[]) {
try {
const fileContents = await Promise.all(filePaths.map(filePath => fs.readFile(filePath, 'utf-8')));
fileContents.forEach((content, index) => {
console.log(`File ${filePaths[index]} content:`, content);
});
} catch (error) {
console.error('Error processing files:', error);
}
}
processFiles(['file1.txt', 'file2.txt']);
总结
async/await
是 TypeScript 中处理异步操作的强大工具。它让异步代码更易读、更易维护,同时保留了 Promise 的强大功能。通过本文的学习,你应该已经掌握了 async/await
的基本用法,并能够在实际项目中应用它。
附加资源与练习
- 练习 1:编写一个异步函数,从 GitHub API 获取用户的仓库列表,并打印每个仓库的名称。
- 练习 2:修改上面的天气案例,使其能够处理多个城市的天气数据,并返回一个包含所有城市天气的对象。
如果你想深入了解 async/await
和 Promise 的关系,可以阅读 MDN 文档。