调用Bored API前两次返回undefined问题的修复方案
解决Bored API返回值首次/二次访问undefined的问题
问题根源
你的代码核心问题是异步操作执行顺序错误:boredApiHandler是异步函数,调用后会立刻返回Promise,而你紧接着执行console.log(FinalDate.activity),此时API请求还没完成,FinalDate还是初始的数组[{}],自然访问activity会得到undefined。后续调用时,之前的请求已经完成,FinalDate被更新,所以能正常获取值。另外,初始把FinalDate定义为数组也不合理,Bored API返回的是单个对象,这会导致首次访问时结构不匹配。
修复方案
- 等待异步请求完成后再访问FinalDate:将submit事件处理函数改为async函数,用
await等待boredApiHandler执行完毕。 - 修正FinalDate的初始值:从数组改为空对象,和API返回结构一致。
- 完善错误处理:不要留空catch块,添加错误日志方便调试。
修改后的完整代码
HTML部分(无需修改)
<section > <form action="" class="form__wrapper"> <div class="participants__wrapper"> <label id="participants__label" for="participants">For how much people the activity:</label> <input type="number" id="participants" name="participants"> </div> <div> <label for="price-range" id="price-range__label">Your price range:</label> <input type="range" name="price-range" id="price-range" min="0" max="1" step="0.1"> </div> <div> <button type="submit" id="sumbuit__button">Submit</button> </div> </form> </section>
JavaScript部分
const howMuchPll = document.querySelector(`#participants`); const priceRange = document.querySelector(`#price-range`); const form = document.querySelector(`form`); let valueForPpl = ""; let valueForPriceRange = ""; let FinalDate = {}; // 修正初始值为对象 const boredApiHandler = async () => { try { const mainData = await fetch( `http://www.boredapi.com/api/activity/?participants=${valueForPpl}&price=${valueForPriceRange}` ); const parsedData = await mainData.json(); FinalDate = parsedData; return FinalDate; } catch (err) { console.error("API请求失败:", err); // 添加错误日志 } }; const howMuchPllHandler = (e) => { valueForPpl = e.target.value; }; const priceRangeHandler = (e) => { valueForPriceRange = e.target.value; }; howMuchPll.addEventListener(`change`, howMuchPllHandler); priceRange.addEventListener(`change`, priceRangeHandler); // 将事件处理函数改为async,等待异步请求完成 form.addEventListener(`submit`, async (e) => { e.preventDefault(); await boredApiHandler(); console.log(FinalDate.activity); });
额外优化建议
- 可以在请求过程中添加加载状态,避免用户重复提交。
- 对
participants输入做数值校验,确保传递给API的是有效数字,避免返回错误结果。
内容的提问来源于stack exchange,提问作者just Props
相关产品推荐
相关产品推荐

