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

使用JavaScript Fetch API提取数据时无法获取todos接口Promise结果怎么办

问题解决方法

response.json() 是异步方法,调用后会返回一个Promise对象,需要等待该Promise状态变为fulfilled之后,才能拿到解析完成的接口返回数组数据。你当前的代码直接把未执行完成的Promise传给了veriOlusturucu方法,所以无法调用数组的forEach方法遍历。

修改方案

首先修改todosApi方法的调用逻辑,等待response.json()执行完成后再传递数据:

const todosApi = (element) =>{
    fetch(`https://jsonplaceholder.typicode.com/todos/?userId=${element.id}`)
    // 先等待response.json()执行完成,拿到解析后的数组
    .then(response=>response.json())
    // 把解析完成的todo数组传给veriOlusturucu
    .then(todoData => veriOlusturucu(todoData, element))
    .catch(e=>console.log(e));
}

可选优化点

  • 你当前的DOMContentLoaded事件绑定存在问题,addEventListener的第二个参数需要传入函数引用,你现在的写法是直接执行了usersApi,修正写法如下:
document.addEventListener('DOMContentLoaded', usersApi);
  • 可以在veriOlusturucu方法里先对传入的todo参数做类型判断,避免接口异常时报错:
const veriOlusturucu = (todo,element) => {
    // 增加类型校验
    if(!Array.isArray(todo)) {
        console.error('todo数据格式错误', todo);
        return;
    }
    // 原有逻辑保持不变
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:45:04