Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting JSON from Fetch API

Tags:

javascript

I realise very similar questions have been answered before, but I'm still finding it very confusing as to how this works...

From my understanding promises are used to deal with asyc requests - these promises essentially send back the state or a "promise" that at some point later a JSON body (or other object) will be delivered.

What I'm trying to understand is how I properly handle these requests so that the function doesn't return until the JSON body is ready to be parsed.

Below I'm trying to simply extract the key "result" (which returns a string "result") and parse it to another variable that can be stored and then later used somewhere else in my code. Unfortunately, my code always returns a [Object Promise], rather than the extracted JSON. I believe this is because response.json is also a promise... however, I don't understand how I get out of the "chain of promises" and return a value that I can actually do something with.

Thanks for any advice,

async function name() {
    const response = await fetch('https://xxxxx.herokuapp.com/timespent', {});
    const json = await response.json();

    return json.result;
}

let varr = name();
console.log(varr)
like image 319
Hazzamataza Avatar asked Jun 13 '26 22:06

Hazzamataza


1 Answers

Since your function is async it always return a promise. You need to use await for result.

read more about async here

async function name() {
  const response = await fetch('https://mautargets.herokuapp.com/timespent', {});
  const json = await response.json();
  return json.result;
    }

async function result(){
  //await can only be called from inside of async function. So we need async function for await name()
  
  let varr = await name();
  console.log(varr)  // Success
}

result()
like image 82
Ashish Avatar answered Jun 18 '26 00:06

Ashish