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
});
2
  • Does this answer your question? How to return the response from an asynchronous call Commented Nov 21, 2021 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. Commented Nov 21, 2021 at 13:15

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

WOW!!!! This worked!! :))) But how??
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!! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.