javascript - Uncaught in promise
问题描述
So I'm fairly new to JavaScript, i had a text document full of nouns, and thought what a good way to create an api with these nouns.
I read the file and added them to a List
public List<Noun> getData() throws IOException {
Scanner sc = new Scanner(new
File("C:\\Users\\Admin\\Desktop\\nounlist.txt"));
List<Noun> nouns = new ArrayList();
while (sc.hasNextLine()) {
nouns.add(new Noun(sc.nextLine()));
}
return nouns;
}
This list i converted to Json with Gson:
@GET
@Path("/nouns/amount=all")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response getAllNouns() throws IOException {
return Response.ok().entity(gson.toJson(nf.getData())).build();
}
I then started to create my frontend with js and tried to fetch the data, but ran into a problem saying uncaught in promise, type error, nouns.forEach is not a function
import "bootstrap/dist/css/bootstrap.css";
const root = document.getElementById("root");
var url = "http://localhost:8084/CORSJavaJax-rs/api/noun/nouns/amount=all";
var tbody = document.getElementById("tbody");
var btn = document.getElementById("btnsend");
// fetch(url)
// .then(res => res.json)
// .then(nouns => {
// var n = nouns.map(noun => {
// return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";
// });
// tbody.innerHTML = n.join("");
// });
btn.addEventListener("click", function() {
fetch(url)
.then(res => res.json)
.then(nouns => {
console.log(nouns);
var n = nouns.forEach(noun => {
return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";
});
tbody.innerHTML = n.join("");
});
});
I tried both with map and forEach but with no succes, maybe im missing something or there is something I just dont understand about why i cannot map the data.
解决方案
对于您想要的,正确的用法是map
调用,而不是forEach
. ForEach 不返回值,它只是在集合上迭代。
您收到is not a function
错误的原因很可能是由于缺少对res.json
. 应该是res.json()
。
btn.addEventListener("click", function() {
fetch(url)
.then(res => res.json())
.then(nouns => {
console.log(nouns);
var n = nouns.map(noun => {
return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";
});
tbody.innerHTML = n.join("");
});
});
推荐阅读
- google-bigquery - Bigquery 上的 EXECUTE IMMEDIATE 位置错误
- reactjs - 使用过滤器从使用状态中删除项目
- mysql - MySQL数据库分析某些表中的问题
- anaconda - 如何使用一个命令行删除多个 conda 环境
- flutter - 如何在 Flutter 屏幕中制作具有多个高光的遮罩?
- arrays - 有人可以告诉我“数组函数如何越界”吗?如果不是,代码是否正确?
- javascript - 重组对象数组,然后对对象进行分组
- python - 如果我安装了两个版本的 cmake,我应该如何让 pip 使用其中一个?
- azure - 如何使用应用程序更改一个租户中的日历条目注册另一个租户
- pandas - 熊猫:如果 dataframe1 中的值 ...THEN 减少 dataframe2 中的值