Home:ALL Converter>How do I async/await an fetch response?

How do I async/await an fetch response?

Ask Time:2022-03-20T14:48:05         Author:hoxy

Json Formatter

I want to use await to save the response to a variable. I need to store that response in a variable and use it in the next code flow. I don't want to store and use variables only inside function braces. In the code below, only one console.log is written, but many events exist. I don't want to use fetch and then. I want to solve it using async/await, but everything I do is wrong. What did I do wrong?

Try 1

Run => Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

var resp = await fetch(`https://www.yahoo.com/manifest_desktop_us.json`);  
var jobj = await resp.json();  
var display = jobj.display;  
console.log(display); //I need display value

Try 2

Run => undefined

async function abc(url) {
  var resp = await fetch(url);
  var jobj = await resp.json();
  return jobj;
}
var url = 'https://www.yahoo.com/manifest_desktop_us.json';
var jobj = abc(url);
//var jobj = async() => await abc(url); //undefined
var display = jobj.display;  
console.log(display); //I need display value

Author:hoxy,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71544663/how-do-i-async-await-an-fetch-response
Siddharth Sathe :

Your 1st try is very much close to get it to work, the error Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules means await can only be used within an async function, so you need to wrap it\n(async function(){\n var resp = await fetch(`https://cors- \n anywhere.herokuapp.com/https://www.yahoo.com/manifest_desktop_us.json`); \n var jobj = await resp.json(); \n var display = jobj.display; \n console.log(display); // logs "standalone" from API\n})();\n\nIn addition, you also need to bypass cors, for the sake of demonstration, I've added cors URL, but in your production app you must handle it in the global HTTP request instance or have your own backend URL.",
2022-03-20T07:16:54
M.A Shahbazi :

You need to move the whole logic related to async operation in an async function.\nYou can use an anonymous async function for that:\n(async () => {\n var resp = await fetch(`https://www.yahoo.com/manifest_desktop_us.json`); \n var jobj = await resp.json(); \n var display = jobj.display; \n console.log(display);\n})();\n\nAlternatively, since an async function returns a Promise you can get the value in a then call as well:\nasync function abc(url) {\n var resp = await fetch(url);\n var jobj = await resp.json();\n return jobj;\n}\nvar url = 'https://www.yahoo.com/manifest_desktop_us.json';\nvar jobj = abc(url).then((value) => console.log(value));\n",
2022-03-20T06:56:18
yy