0

Hi I am trying to fetch a local JSON file I used localhost for this but the problem I am having is when I fetch it using:

const endpoint = "http://127.0.0.1:5500/appendixA.json"

const fetchedItems = fetch(endpoint)
    .then(res => res.json())
    .then(result => result.appendix_a)
    .catch(e => console.log("error: ", e))

or using async await

const fetchFunc = async () => {
     let response = await fetch(endpoint);
     let jsonResponse = await response.json()
     return jsonResponse.appendix_a;
}

So when I console.log either of them console.log(fetchedItems) console.log(fetchFunc()) I am not getting result as a variable array ie [ //results ] But instead I am getting just a [Promise]

Here is a sample off the JSON file

    {
        "appendix_a": [
            {
                "id": 1,
                "stakeholder": "Commercial Director",
                "user_story": "As a user I need to be able to insert my name into the form"
            },
            {
                "id": 2,
                "stakeholder": "Commercial Director",
                "user_story": "As a user I need to be able to insert my email into the form"
            }
        ]
    }

Why is this happening as I have done res.json() on the initial .then call as well as I have done await res.json() inside the async function

Please clarify for me that.

As I plan to insert the fetch data into a ul element like this which obviously wont work because of the Promise

const ul = document.querySelector('ul');
let li = document.createElement('li');

fetchedItems.map(pa => {
        li.innerHTML = `
<span>${pa.id}</span> 
<p>${pa.stakeholder}></p> 
<p>${pa.user_story}</p> `
        return ul.appendChild(li);            
});
Mohamed
  • 425
  • 4
  • 14
  • ALL `async` functions return a promise. The caller of an `async` function MUST use either `.then()` or `await` themselves to know when the asynchronous operation is complete and what it's final value is. So, `fetchFunc()` returns a promise and you have to use `.then()` or `await` on its result. – jfriend00 Mar 06 '22 at 05:02

1 Answers1

1

You're in async world now, so you have to work with callbacks. This:

console.log(fetchedItems)

Becomes:

fetchedItems.then(console.log);

And:

console.log(fetchFunc());

Would be:

fetchFunc().then(console.log);

Or:

console.log(await fetchFunc());
elclanrs
  • 92,861
  • 21
  • 134
  • 171