执行多异步API调用时遭遇Unexpected Identifier错误求助
问题分析与修复方案
兄弟,你这个“Unexpected Identifier”错误的根因太明显了:你在非async函数里用了await!看你代码里的内层forEach回调,就是个普通函数,却直接写了await axios.post(...),JS语法里根本不允许这么干——await必须放在被async标记的函数内部才行。
另外你的代码还有几个坑得顺便填上:
- 外层已经写了
for循环,还嵌套两层forEach,这完全是重复遍历,纯纯的性能浪费; - 用
var声明变量容易踩作用域的坑,换成const/let更稳妥; async函数和callback混着用没必要,async函数本身就返回Promise,直接用Promise的逻辑处理就行。
修正后的代码(串行处理子请求)
async function GetList(req, res) { // 第一次API调用,用const替代var const response = await axios.post("http://someURL.com/GetList", req.body); // 用for...of替代forEach,这样就能在循环里正常用await了 for (const element of response.data) { for (const em of element) { // 这里可以按需处理子请求的结果 const getChildList = await axios.post("http://someURL.com/GetList2", em); // 比如把结果挂到原元素上: // em.childData = getChildList.data; } } // 后续逻辑,比如返回处理后的结果 res.json(response.data); }
如果想提升性能,让所有子请求并行发起(不用逐个等),可以用Promise.all:
async function GetList(req, res) { const response = await axios.post("http://someURL.com/GetList", req.body); // 先把所有子请求都收集成Promise对象 const childRequestPromises = []; for (const element of response.data) { for (const em of element) { childRequestPromises.push(axios.post("http://someURL.com/GetList2", em)); } } // 一次性等待所有请求完成 const childResponses = await Promise.all(childRequestPromises); // 把响应结果对应回原数据(如果需要的话) let responseIndex = 0; for (const element of response.data) { for (const em of element) { em.childData = childResponses[responseIndex].data; responseIndex++; } } res.json(response.data); }
划重点的知识点
- 别在
forEach的回调里用async/await!哪怕你把回调改成async,forEach也不会等待异步操作完成,会导致逻辑乱套; - 处理异步循环,优先选
for...of(串行,适合有依赖的请求)或Promise.all(并行,适合无依赖的请求,速度更快); async函数就别掺和传统回调了,直接用Promise的特性处理异步流程,代码更清爽。
内容的提问来源于stack exchange,提问作者Benjamin
相关产品推荐
相关产品推荐

