Javascript如何将获取数据推送到数组

时间:2021-06-24 23:31:57

标签: javascript arrays fetch fetch-api

我只是在回顾一些基本的 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()

提前致谢

1 个答案:

答案 0 :(得分: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);
    });
}
相关问题