3

I'm just recapping some basic javascript any idea where i am going wrong?, i want to receive the response and place it into an array inside the function. The below is what i have tried.

  // 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 Answers1

1

You're getting tripped up by Promises!

Basically, you're calling console.log(a) before a.push(data) gets called because the then handlers get called asynchronously.


If you want to use the response from fetch in another function, there's multiple ways you can do it in Javascript. As @Matt linked in the comment, this question goes in great depth on how to do that.

The simplest way? Update your abs function to accept an argument handler and pass the data to the 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);
    });
}
Kaeden Wile
  • 101
  • 1
  • 5