Home:ALL Converter>How to store fetch response in javascript variable

How to store fetch response in javascript variable

Ask Time:2021-12-14T21:42:34         Author:Amara

Json Formatter

sorry for the basic question. I was trying using fetch to get data from api and want to store that response into a javascript variable but its not working as I have expected My code-

async function fun() {
    var a = "initial";
    fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(res => res.json())
        .then(data => {
            a = data;
            console.log(a);
        })

    await console.log("Response => ", a);
}

Output - Response => initial

What is the correct way of doing this.

Author:Amara,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70349865/how-to-store-fetch-response-in-javascript-variable
Caulic :

You may need to add await before fetch.\nasync function fun() {\n var a = "initial";\n await fetch('https://jsonplaceholder.typicode.com/todos/1')\n .then(res => res.json())\n .then(data => {\n a = data;\n console.log(a);\n })\n\n console.log("Response => ", a);\n}\n",
2021-12-14T13:52:16
yy