【问题标题】:Javascript how to push fetch data to an array [duplicate]Javascript如何将获取数据推送到数组[重复]
【发布时间】:2021-09-08 10:06:54
【问题描述】:

我只是在回顾一些基本的 javascript,知道我哪里出错了吗?我想接收响应并将其放入函数内部的数组中。以下是我尝试过的。

  // simple api request
    
    function abs() {
    var a = []
    fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(res => {return res.json()})
    .then(data =>  a.push(data)) 
    
    console.log(a)

}


abs()

提前致谢

【问题讨论】:

    标签: javascript arrays fetch fetch-api


    【解决方案1】:

    你被 Promises 绊倒了!

    基本上,您调用console.log(a) 之前 a.push(data) 被调用是因为then 处理程序被异步调用


    如果您想在另一个函数中使用来自fetch 的响应,您可以通过多种方式在 Javascript 中实现。正如@Matt 在评论中链接的那样,this question 深入探讨了如何做到这一点。

    最简单的方法?更新您的 abs 函数以接受参数 handler 并将数据传递给处理程序:

    // handler is a function that accepts an array
    function abs(handler) {
        fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(res => {return res.json()})
        .then(data => {
            var a = [];
            a.push(data);
            handler(a);
        });
    }
    

    【讨论】:

    • 谢谢,是的,console.log 是用于测试目的,我只是希望函数中的数组与数据一起返回
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2021-08-17
    • 2016-12-23
    • 2022-01-18
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多