Search code examples
javascriptnode.jsjsonasynchronousfetch

JSON.parse(Fetch_Get_JSON_Data) Within Async Function


I stumbled across an issue where I was trying to parse an incoming .JSON object in an async Fetch-Get request, it gave me the following error in the browser:

Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at window.getData (Login.js:32)
    at async window.login (Login.js:38

This is the relevant pre-browserified code:

window.getData = async function()
{
var response = await fetch("https://goldengates.club:3000/api/blocks");
var chain = await response.json();
var chainParsed = JSON.parse(chain);
return chainParsed;
}

window.login = async function()
{
  const chain = await getData(); //might need to parse this
  console.log(chain);
}

The login function above gets called once a button is pressed in the front end.

I am obviously doing something wrong and it's bugging me, I am fairly new to asynch and any help is greatly appreciated.


Solution

  • Seems like the error is coming up due to the last two lines in windows.getData.

    Incase your motive was to return the properties from that api mentioned in var response.

    const url = ""https://goldengates.club:3000/api/blocks"";
    
    window.getData = async () => 
    {
    var response = await fetch(url);
    var chain = await response.json();
    
    return (
    {chain.map((everyChain) => {
    const { timestamp, lasthash, hash, data, nounce, difficulty, type } = everyChain;
       return everyChain;
     }});
    }