Hi guys, I retrieved data from server with the ajax method but I don't know how to extract this data out of response text to use it somewhere else. Any suggestions how to do this would be greatly appreciated. fetch("/path_to_file/data.json").then(response => { return response.text(); }).then(data => { if(data) { var foo = JSON.parse(data); console.log(data); // {"key1":"value1","key2":"value2"} retrieveData(foo.key1,foo.key2); } }); function retrieveData(x,y) { var data = { a: x, b: y }; return data; } var ax = retrieveData.a; console.log(ax); // => not working Code (markup): Thank you,
It's because lines 14 & 15 are outside the ajax block, I guess. What would happen if you put them inside retrieveData()? function retrieveData(x,y) { var data = { a: x, b: y }; console.log(data); return data; } Code (markup):
Ok, I got this. Something called a callback comes to rescue: function fABC(file, callback) { fetch(file).then(response => { return response.text(); }).then(data => { if(data) { var foo = JSON.parse(data); callback(foo); } }); } var string = fABC("/path_to_file/data.json", function(ss){ console.log(ss); // wooohsa, this takes me two days... ); }); Code (markup):
All of which being a stunning example of why fetch isn't an improvement over XMLHttpRequest. Particularly when it has no mime-type juggling/setting, no response code handling, etc, etc. Much less that derpy daisy chaining "then then then" promises and arrow function junk that just makes things harder to deal with and introduces overhead for nothing. Though even using fetch/then, why the extra routine? function fABC(file, callback) { fetch(file).then(function(response) { callback(JSON.parse(response.text())); }); } Code (markup): Cutting out all the excess junk. Of course once you have it down that small, one has to question why bother making it a standalone function instead of just putting it where you call it. fetch('/path_to_file/data.json').then(function(response) { var string = JSON.parse(response.text); console.log(string); }); Code (markup): The laugh being that just manually doing the fetch/then directly instead of in a function ends up the same size as your var string= code, meaning there's not really a legitimate excuse to even make that fABC function. Hell it would be smaller if one used the arrow function mental midgetry.
Thank you @deathshadow, I like both the abridge versions. However, the first one threw an error. The response.text of the second one is something this: ƒ text() { [native code] } Code (markup): I think it's a function so it cannot be parsed but I'm going to modify it. Let's see if I can make it worked.