为什么带await的异步请求未等待响应,数组填充前就打印长度为0
问题原因
JS执行时会优先跑完所有同步代码,再执行异步回调。你调用postData后,网络请求还在后台处理,.then里填充CardsID的逻辑还没触发,后面的console.log就已经执行完了,所以拿到的是空数组的长度。你看到的控制台先输出0、空数组,之后才打印24条added就是这个执行顺序导致的。
解决方法
方案1:把依赖CardsID的逻辑放到.then回调中
const url = "[LL_REPTAG_URLPREFIXFULL /]/api/v2/businessworkspaces?where_workspace_type_id=54"; const CardsID = []; async function postData() { let response = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json", OTCSTicket: "[LL_REPTAG_OTCSTICKET /]", }, }); return await response.json(); } postData().then(function (data) { data.results.forEach((element) => { CardsID.push(element.data.properties.id); console.log("added"); }); // 所有依赖填充完成后CardsID的逻辑都写在这里 console.log(CardsID.length); console.log(CardsID); });
方案2:用async立即执行函数+await,写法更符合线性阅读习惯
把你之前注释的代码放开,按如下调整即可:
const url = "[LL_REPTAG_URLPREFIXFULL /]/api/v2/businessworkspaces?where_workspace_type_id=54"; const CardsID = []; async function postData() { let response = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json", OTCSTicket: "[LL_REPTAG_OTCSTICKET /]", }, }); return await response.json(); } (async function(){ const data = await postData(); data.results.forEach((element) => { CardsID.push(element.data.properties.id); console.log("added"); }); // 此处CardsID已经填充完成 console.log(CardsID.length); console.log(CardsID); })();
内容的提问来源于stack exchange,提问作者HamoudyMulti
相关产品推荐
相关产品推荐

