You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery中异步fetch获取JSON对象后无法用$.each遍历怎么解决?

问题根源

  • async修饰的函数默认返回Promise对象,你直接执行var json = listFiles('images')拿到的不是请求返回的JSON数据,是处于pending状态的Promise实例。执行$.each的时候异步请求还没有完成,自然没有办法遍历还没拿到的数据集。
  • 你看到console.log(json)能展示完整内容是浏览器控制台的特性:打印引用类型数据时,只有你手动展开打印结果的那一刻才会读取变量的最新值,你展开的时候请求已经完成,所以会误以为代码执行到打印这步时就已经拿到了数据,属于视觉误导。

修复方案

可以任选以下两种写法中的一种:

写法1:在DOM就绪回调中使用await获取异步结果

async function listFiles(dir){
  try {
    const response = await fetch('action.php', {
      method: 'POST', 
      mode: "same-origin",
      credentials: "same-origin",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({dir:dir})
    })
    const data = await response.json()
    console.log('Success:', data);
    return data
  } catch (error) {
    console.error('Error:', error);
  }
}

// 给回调函数加async修饰,内部就可以用await拿异步结果
$(async () => {
  const json = await listFiles('images');
  $.each(json, function(index,val){
    console.log("index: "+index+"; value: "+val); 
  })
  console.log(json);
});

写法2:通过.then链式调用处理返回结果

// listFiles函数不用改,直接在调用后用.then处理结果
$(() => {
  listFiles('images').then(json => {
    $.each(json, function(index,val){
      console.log("index: "+index+"; value: "+val); 
    })
    console.log(json);
  })
});

额外注意

如果要确认代码执行到某一步时变量的实际值,不要直接打印引用类型,改成console.log(JSON.stringify(json))打印序列化后的结果,就能看到执行$.each时变量还不是你需要的数组/对象结构。

内容的提问来源于stack exchange,提问作者v01d

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:06:04