Home > Blockchain >  Printing an object from json in js
Printing an object from json in js

Time:03-10

I have some info in JSON form fethced from my api, now I want to console.log a specific object from it, I have tried a few ways, but I get either undefined or the whole JSON text printed out The code I have right now:

const api_url = 'http://127.0.0.1:8000/main/';

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

getapi(api_url);

var results = getapi(api_url);

console.log(results);

I just started working with apis and async js I would love to get some help.

CodePudding user response:

The console.log is running at compile time, so in order to handle a synchronous function, you need to do something like:

const api_url = 'http://127.0.0.1:8000/main/';

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

getapi(api_url).then(res => console.log(res));

The then tells the compiler to wait for the async function to return a value, similarly to how await in the function is waiting for the response to return from the server.

CodePudding user response:

async functions will always return a promise. fetch returns a promise. Even .json() will return one. So just return the parsed data from the function, await that, and then log the data.

Here's the useful MDN documentation.

const api_url = 'http://127.0.0.1:8000/main/';

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

async function main() {
  const data = await getapi(api_url);
  console.log(data);
}

main();

  • Related