【问题标题】:Uncaught in promise未兑现承诺
【发布时间】:2025-12-02 00:55:02
【问题描述】:

所以我对 JavaScript 还很陌生,我有一个充满名词的文本文档,我想用这些名词创建一个 api 的好方法。

我阅读了文件并将它们添加到列表中

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;
}

这个列表我用 Gson 转换成 Json:

@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();
}

然后我开始用 js 创建我的前端并尝试获取数据,但遇到了一个问题,说 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("");
    });
});

我尝试了 map 和 forEach 都没有成功,可能是我遗漏了什么,或者我只是不明白为什么我无法映射数据。

【问题讨论】:

  • 如果你console.log,res.json的打印值是多少?
  • console.log(nouns) 打印什么?看起来它不是一个数组。 forEach 是一个数组方法。

标签: javascript java rest


【解决方案1】:

对于您想要的,正确的用法是调用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("");
    });
});

【讨论】:

  • 哦哇哦,我现在觉得自己好蠢,我总是对这样的事情视而不见。感谢您教我什么是正确用法,并发现我的错误!
  • 很高兴能帮上忙!公正的眼睛总是有助于解决这些“盯着自己瞎”的情况:)
  • 如果它解决了问题,您应该接受答案以确保更新 SO 历史记录
  • 很好的解释
最近更新 更多