13

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"

Aessandro
  • 5,517
  • 21
  • 66
  • 139

1 Answers1

22

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);
    });
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
  • 4
    why is this marked as duplicate linked to a question from 2013? – loag Oct 25 '17 at 04:51
  • 2
  • @loag because [this thread](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) is a canonical dupe for the legions of questions that exhibit this identical pattern. The canonical offers an extremely thorough treatment of the problem, saving everyone time. It's a disservice to reinvent the wheel each and every time this question pops up. – ggorlen Jul 26 '21 at 01:22