async/await 为什么没按顺序执行?

UI春彦 阅读 5

我写了个函数想依次请求两个接口,但发现第二个请求没等第一个完成就发出去了,是不是 async/await 用错了?

我试过把 await 放在 fetch 前面,也确认函数是 async 的,但还是不行。

async function fetchData() {
  fetch('/api/user').then(res => res.json());
  fetch('/api/profile').then(res => res.json());
}
我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
轩辕诗雅
你 fetch 请求后面忘了加 await,省事的话改成这样:
async function fetchData() {
await fetch('api/user').then(res => res.json());
await fetch('api/profile').then(res => res.json());
}
点赞
2026-03-22 11:18