## 前言
从回调函数到 Promise,再到 async/await,异步编程的写法越来越优雅。
## 回调函数
```javascript
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
```
## Promise
```javascript
fetch('/api/user')
.then(res => res.json())
.then(user => fetch(`/api/posts?userId=${user.id}`))
.then(posts => console.log(posts))
.catch(err => console.error(err));
```
## async/await
```javascript
async function getPosts() {
try {
const res = await fetch('/api/user');
const user = await res.json();
const postsRes = await fetch(`/api/posts?userId=${user.id}`);
console.log(await postsRes.json());
} catch (err) {
console.error(err);
}
}
```