JavaScript如何将获取的数据推送到数组中

3

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

Thanks in advance

1个回答

1

你被Promise绊倒了!

基本上,由于then处理程序是异步调用的,所以在a.push(data)被调用之前,你会在console.log(a)之前调用它。


如果你想在另一个函数中使用来自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 仅用于测试目的,我只想从函数返回数组与数据。 - code_novice_1234

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接