Populate a Select Dropdown Lists from JSON variable , with sync / await

I am performing a test, where I have to populate a form and take the options data from a given object that resides on a external file. The idea is to fetch this data in order to populate two drop down select lists, one for the chousen state and the other for its corresponding cities and the way to achieve this, should be by making use of the async / await methods and try and catch statements. Here’s the json file data.js:

var stateLocs = {
    "California":["Los Angeles","San Diego"],
    "Georgia":["Atlanta", "Augusta"],
    "New York":["New York City","Buffalo","Rochester"]

And this is what I’ve done so far, as retrieves me an error:

const getDataAsync = async () => {
  try {
    const res = await fetch("/js/data.js")
    const data = await JSON.parse()

    data.results.map(stateLocs => console.log(stateLocs))
  } catch (err) {
    const errorObject = JSON.parse(err);

This is the error it throws form a Firefow browser:

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

    getDataAsync http://localhost:3000/js/scrypts.js:9
    async* http://localhost:3000/js/scrypts.js:13
    getDataAsync http://localhost:3000/js/scrypts.js:10
    AsyncFunctionNext self-hosted:690
    (Asíncrono: async)
    <anonymous> http://localhost:3000/js/scrypts.js:13

I think this is due to the fact that the json is actually inside an object and I am not accessing it in the correct way…
I have also tried in this other way, but it keeps failing, with a Failing Request

const getData = async () => {
try { 
const res = await fetch("./js/data.js"); 
let data = JSON.parse();
 data = (stateLocs) => { for (const stateLocs in data) {
 if (data[stateLocs]) { console.log(${data.stateLocs}, ${data[stateLocs]});
 } } }; } catch (err) { console.log("The request failed!");

The first line is correct. The problem is with the second line. You want to parse the response you get from fetch. Right now you aren’t parsing anything, you are just calling JSON.parse() with no arguments, which is what is causing the error you are getting. This page has the exact example of using fetch with async/await that you will want to follow for your own code.

1 Like

Thank you so much for your help!