gpt4 book ai didi

javascript - 获取异步/等待数据并以 html 格式显示/返回

转载 作者:行者123 更新时间:2023-11-30 19:12:13 25 4
gpt4 key购买 nike

我是异步/等待获取的新手。下面是我的 HTML 代码

  <div id="content">
<!-- Data will appear here as list -->
</div>

下面是我的 vanilla JS 代码

function loadData() {
const element = document.getElementById("content");
element.innerHTML = getTemplate();
}

function getTemplate() {
async function getPosts() {
try {
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);
console.log(response);

if (response.ok) {
const res = await response.json();
return res;
} else {
throw new Error(response.statusText);
}
} catch (error) {
return error;
}
}

getPosts().then(data => console.log(data));

//How I return data from here so it will update in the DOM

};

loadData();

如何在使用 vanilla JS 异步/等待获取我的数据后将数据显示为列表。

最佳答案

如果重新组织一下代码没有问题,请尝试以下操作。关于如何返回,请记住异步函数返回一个 promise ,并且您必须在上下文中工作,所以我得到了调用 getPosts 的响应 promise ,并使用数据获得了模板,然后将其提供#内容

function loadData() {
const element = document.querySelector("div#content");

getPosts().then(posts => {
const template = getTemplate(posts);

element.innerHTML = template;
});
}

async function getPosts() {
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);

return await response.json();
}

function getTemplate(posts) {
const rows = posts.map(postToRowView).join("");

return `<table>
<thead>
<tr>
<th>Title</th>
<th>Body</th>
</tr>
</thead>

<tbody>${rows}</tbody>
</table>`;
}

function postToRowView(post) {
return `<t>
<td>${post.title}</td>
<td>${post.body}</td>
</tr>`;
}

loadData();
<div id="content"></div>

关于javascript - 获取异步/等待数据并以 html 格式显示/返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58360029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com