-1

I am wondering why am I not able to get the array after I returned its values from the function? The output on the console is an empty array.

function fetchdates(){
        let theDateTime,DatesSepTime,Dates = [];

        fetch("./myfile.json")
        .then((resp) => {
            return resp.json();
            })
        .then((data) => {
            for(let obj of data){
                let theDateTime = obj.tweetcreatedts;
                let DatesSepTime = theDateTime.split(" ");
                let Dates = DatesSepTime[0];
                //console.log(Dates);
                }
            })
        
        return(Dates);
        };
    console.log(fetchdates());
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Mar 18 '21 at 21:07
  • Read up on how async code is processed in node – Dominik Mar 18 '21 at 21:07
  • Your scope is additionally wrong - `let Dates` is declared inside of the loop block of the `then` callback. – ASDFGerte Mar 18 '21 at 21:08

1 Answers1

1

Fetch is asynchronous.

This means, it immediately returns, and the function execution will resume when the asynchronous operation completes. So if you log instatly the return value, of course it wont contain the processed values.

Aside from that,you have another issue which is declaring the Dates variable two times (you do this to the others as well btw, its unnecessary)- first its an empty array (thats why it gets returned immediately and that is why you get empty array as a result), then you assign it a different value, but that is only happening when the async method execution resumes.

I would suggest to read this: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Vendel Serke
  • 117
  • 8