Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 fetch function returns undefined [duplicate]

Tags:

javascript

I have the following code:

        function fetchDemo() {
            var result;
            fetch(countriesUrl).then(function(response) {
                return response.json();
            }).then(function(json) {
                result = json;
            });

            return result;
        }

        console.log(fetchDemo());

console.log(fetchDemo()) the following returns undefined. I need to use that value inside another function.

The URL is "https://rawgit.com/csabapalfi/20d74eb83d0be023205225f79d3e7964/raw/7f08af5c0f8f411f0eda1a62a27b9a4ddda33397/countries.json"

like image 441
Aessandro Avatar asked Sep 20 '16 10:09

Aessandro


1 Answers

fetchDemo is doing async work. So to see the result you must chain the promise:

    function fetchDemo() {
        return fetch(countriesUrl).then(function(response) {
            return response.json();
        }).then(function(json) {
            return json;
        });
    }

    fetchDemo().then(function(result) {
        console.log(result);
    });
like image 100
Davin Tryon Avatar answered Oct 13 '22 14:10

Davin Tryon