0

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

komote7665
  • 31
  • 6

1 Answers1

0

Just write the one function, you dont need to write two functions.

async function getJsonPromise(url) {
        const response = await fetch(url);
        return response.json();
    }

and when you call function just call it like given below.

getJsonPromise().then((response)=>{
            console.log("Data: ",response.data)
        })
Swanand Taware
  • 723
  • 2
  • 7
  • 32
  • but I want it all inside the function, I don't want to use then or anything else outside, I want a getJson function that brings me the json directly (If that is possible..) – komote7665 Jan 27 '23 at 04:38
  • I also wanted functions with the 2 syntaxes more for learning, to get used to it – komote7665 Jan 27 '23 at 04:39