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

UI春彦 阅读 76

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

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

async function fetchData() {
  fetch('/api/user').then(res => res.json());
  fetch('/api/profile').then(res => res.json());
}
我来解答 赞 6 收藏
二维码
手机扫码查看
2 条解答
Prog.梓桑
你在代码里虽然用了 async 函数,但没有真正利用 await 的特性。要让两个请求按顺序执行,每个 fetch 都需要单独用 await 来等待完成。

这样改写试试:
async function fetchData() {
let userResponse = await fetch('/api/user');
let userData = await userResponse.json();

let profileResponse = await fetch('/api/profile');
let profileData = await profileResponse.json();
}


注意几个点:首先每个 fetch 后面都要跟 await,这样才能保证顺序执行。另外别忘了处理可能的异常,实际开发中最好加上 try...catch 结构。

这其实是个常见的误区,很多新手以为只要在函数前加 async 就万事大吉了。其实 async 只是允许你用 await,真要控制异步流程还得靠 await 自己。

我以前也犯过这种错,调试了半天才发现问题出在这儿,挺烦人的。不过现在都养成习惯了,写异步代码第一反应就是检查 await 放对地方了没。
点赞
2026-03-27 06:06
轩辕诗雅
你 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