How to convert this PromiseResult Object to an Array?

Viewed 15120

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.

2 Answers

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();
})();

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.

Related