Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  44] [ 7]  / answers: 1 / hits: 17527  / 8 Years ago, tue, september 20, 2016, 12:00:00

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


More From » javascript

 Answers
3

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);
});

[#60667] Friday, September 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anitamaeg

Total Points: 466
Total Questions: 106
Total Answers: 106

Location: Suriname
Member since Sun, Jun 13, 2021
3 Years ago
;