获取本地JSON文件时出现Promise问题,无法正常工作



嗨,我正在尝试获取一个本地JSON文件,我为此使用了localhost,但问题是当我使用获取它时

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))

或使用异步等待

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

所以当我安慰他们时console.log(fetchedItems)console.log(fetchFunc())我没有得到作为变量数组的结果,即[//results]但我得到的只是一个[承诺]

以下是JSON文件的示例

{
"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"
}
]
}

为什么会发生这种情况,就像我在initial.then调用中做了res.json()一样,以及我在异步函数中做await res.json()一样

请帮我澄清一下。

当我计划将fetch数据插入到这样的ul元素中时,由于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);            
});

您现在处于异步世界中,因此必须使用回调。此:

console.log(fetchedItems)

成为:

fetchedItems.then(console.log);

和:

console.log(fetchFunc());

将是:

fetchFunc().then(console.log);

或者:

console.log(await fetchFunc());

最新更新