trying to use await/async with fetch's promises

Viewed 35

learning some javascript, and I have a question. Can someone explain me why this code print correctly the json file stored in my URL

async function getResponse() {
    const response = await fetch(
        'https://jsonplaceholder.typicode.com/todos/1',
        {
            method: "GET"
        }
    );
    const response2=await response.json();
    console.log(response2);

}

getResponse();

while this

async function getResponse() {
    const response = await fetch(
        'https://jsonplaceholder.typicode.com/todos/1',
        {
            method: "GET"
        }
    );
    const response2=await response.json();
    return response2;
}

console.log(getResponse());

return me a promise instead? In the second case, I tried to get the json file out of the function without success. I tried also

console.log(await getResponse());

but it doesn't seem to bother. It gives me instead a syntax error since he think I m adding 2 arguments without commas. Any idea of the correct way to do this without using then-catch? (to clear any clue, the fetch call, retrieve a json file stored in a local server I created on that URL with node.js)

0 Answers
Related