JavaScript中for循环被跳过/无法运行的问题排查
问题原因
你直接把fetchIngredients()的返回值传给了displayIngredients,但async函数执行后返回的是Promise对象,不是你期望的数组。Promise对象没有length属性,所以循环条件i < ingredients.length会变成i < undefined,直接不满足,循环就被跳过了。
解决方案
有两种常见的修正方式:
方式一:用await获取Promise结果
async function fetchIngredients() { let response = await fetch('/Ingredients/GetAll'); let jsonResult = await response.json(); console.log(jsonResult); return jsonResult; } // 用await获取实际的数组,需要放在async函数里执行 async function init() { let ingredients = await fetchIngredients(); displayIngredients(ingredients); } async function displayIngredients(ingredients) { let ingredientsContainer = document.getElementById("ingredients-container"); for (var i = 0; i < ingredients.length; i++) { // 这里写你的DOM操作逻辑,比如: let item = document.createElement('div'); item.textContent = ingredients[i].Name; // 假设你的对象有Name属性 ingredientsContainer.appendChild(item); } } // 初始化执行 init();
方式二:用.then链式调用
async function fetchIngredients() { let response = await fetch('/Ingredients/GetAll'); let jsonResult = await response.json(); console.log(jsonResult); return jsonResult; } async function displayIngredients(ingredients) { let ingredientsContainer = document.getElementById("ingredients-container"); for (var i = 0; i < ingredients.length; i++) { // 这里写你的DOM操作逻辑 let item = document.createElement('div'); item.textContent = ingredients[i].Name; ingredientsContainer.appendChild(item); } } // 用.then获取Promise的结果后再调用displayIngredients fetchIngredients().then(ingredients => { displayIngredients(ingredients); });
关键说明
async函数的返回值永远是Promise,必须通过await(只能在async函数内使用)或者.then()才能拿到实际的返回数据。- 你提供的截图里的对象确实是数组,只要拿到这个数组本身,循环就能正常执行。
内容的提问来源于stack exchange,提问作者Gurfulhete
相关产品推荐
相关产品推荐

