I want a function that returns a json from a given url using the fetch api (and also if you have a better API option, please tell me, because I'm still learning about promises and etc.)
What I tried:
// [1] with await, I couldn't return, just print on the console
// what needs to change to be able to return instead of printing???
function displayJson1(url) {
async function getJsonPromise(url) {
const response = await fetch(url);
const promise = response.json(); // should i put an await here?? the result was the same
return promise;
}
const promise = getJsonPromise(url);
promise.then((data) => console.log(data));
}
// [2] with .then, I couldn't return, just print on the console
// what needs to change to be able to return instead of printing???
function displayJson2(url) {
const fetchPromise = fetch(url);
fetchPromise
.then((response) => response.json())
.then((data) => console.log(data))
}
in both cases I tried replacing
console.log(data)
by
let json;
json = data;
return json;
But for some reason it didn't work, if you could also explain to me why json = data
didn't work I would be grateful.
What i expected/wanted to happen: return the JSON (with the fetch API, using then or await, and if you can show me how I can make the 2 functions return a JSON with both syntaxes it would be even better to learn!)
what actually resulted: both functions, displayJson1
and displayJson2
are printing the JSON (when in fact I just wanted to return the JSON)
in short, instead of displayJson1
and displayJson2
functions I want getJson1
(using await) and getJson2
(using .then) functions