6

I've successfully retrieved a promise from this async/await function:

  const fetchJSON= (async () => {
      const response = await fetch('http://localhost:8081/getJavaMaps')
      return await response.json()
  })();

Now I want to convert or assign the result to an array. This is what the result looks like in the console.log(fetchJSON):

[[PromiseResult]]: Object
One: "Batman"
Three: "Superman"
Two: "Ironman"

However when I perform operations like: console.log(fetchJSON.One); console.log(fetchJSON.length);

I always get:

undefined

I've tried this:

 let myarray = Object.entries(fetchJSON);

But it doesnt convert the PromiseResult Object to 2d arrays.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Adi Mabfalin
  • 316
  • 2
  • 3
  • 12

2 Answers2

3

All asynchronous functions must be resolved using the await statement or then chain. You cannot get the result of an asynchronous function in synchronous code.

(async()=>{
   const arr= await fetchJSON();
})();
Dmitriy Mozgovoy
  • 1,419
  • 2
  • 8
  • 7
-1

You made fetchJSON to a function. Thus the return will not go back to fetchJSON. You have to handle it like this:

let myResult;
fetchJSON()
    .then((result) => {
        console.log(result);
        myResult =  result;
    })
    .catch((error) => {
        console.log(error);
    });

or

    let myResult = async fetchJSON()
                       .catch((error) => {
                             console.log(error);
                             });
    console.log(JSON.stringify(myResult));

Unhandled promises are already deprecated. Don't just async/await! Catch your errors! You have at least a catch-block to handle errors.

nologin
  • 1,402
  • 8
  • 15