0

I am first time using Async/Await in JS so I am confused little bit. I need to fetch JSON object from test API and store it somehow into global variable so I can use it outside async function, tried many solutions found on google but whatever I tried I am getting undefined, empty array or in most cases - Promise {}

My code currently looks like this:

let myArray = [];

async function fetchExam(id) {
  try {
      const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
          method: 'GET',
          credentials: 'same-origin'
      });
      const exam = await response.json();
      return exam;
  } catch (error) {
      console.error(error);
  }
}

async function renderExam(id) {
  const exam = await fetchExam(id);
  console.log(exam);
}

renderExam()
console.log(renderExam())

I just want to assign JSON object hold in variable exam - to array called myArray. Last line returns Promise {} and console.log in renderExam function returns valid JSON. So, I need that JSON outside of async functions.

punky
  • 125
  • 2
  • 12
  • you have to use a main async wrapper or .then(). also you over assigning vars, instead of `const exam = await response.json();` you can do `return response.json();` you don't need to await – Lawrence Cherone Nov 27 '21 at 14:09
  • `Last line returns Promise {} and console.log in renderExam function returns valid JSON` that is expected as renderExam is asynchronous. You will have to set your array and console.log within the function. – Suraj Rao Nov 27 '21 at 14:10
  • 1
    [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Andreas Nov 27 '21 at 14:17

0 Answers0