1

I have an issue with iterating json object in jQuery after fetching asynchronly. With async function 'listFiles' I managed to succesfully get the desired filelist of directory (dir), at least console.log shows json with content. But when I try to call $.each on fetched filelist json object, $.each simply doesn't work. The console.log inside $.each function should output something.

async function listFiles(dir){
  var json_data = await fetch('action.php', {
    method: 'POST', 
    mode: "same-origin",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({dir:dir})
  })
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
    return data
  })
  .catch((error) => {
    console.error('Error:', error);
  });

  return json_data;
}

var json = listFiles('images');

$(() => {
  $.each(json, function(index,val){ //this function doesn't work, dunno why :(
    console.log("index: "+index+"; value: "+val); 
  })

  console.log(json); //this shows fetched json object's content
});
v01d
  • 147
  • 11
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – pilchard Nov 21 '21 at 12:33
  • Did you read the linked duplicate? You need to `await` the return of `listFiles` or put your iteration callback in a `then` statement. Once in async land always in async land. – pilchard Nov 21 '21 at 13:15

1 Answers1

2

You code should look something like below, you were using async-await and also using callbacks, and also you were printing data when it was not available.

async function listFiles(dir) {
    try {
        const response = await fetch('action.php', {
            method: 'POST',
            mode: "same-origin",
            credentials: "same-origin",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ dir: dir })
        })
        const json_data = await response.json();
        console.log('Success:', json_data);

        return json_data;
    }
    catch (error) {
        console.error('Error:', error);
    }

}

async function printJsonData() {
    var json = await listFiles('images');

    $.each(json, function (index, val) { // now it should work :)
        console.log("index: " + index + "; value: " + val);
    })

    console.log(json); //this shows fetched json object's content
}

printJsonData();
Abdur-Rehman M
  • 311
  • 1
  • 6
  • WOW!!!! This worked!! :))) But how?? – v01d Nov 21 '21 at 13:36
  • Oh I see! I didn't store data in const variable asynchronly with await json.response in try statement and much more. Oh gosh, what do I know now. Thanks man!! :) – v01d Nov 21 '21 at 13:45