Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

javascript - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...