没兑现承诺

时间:2019-03-10 13:48:06

标签: javascript java rest

因此,我对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创建前端并尝试获取数据,但是遇到一个问题,说未兑现promise,类型错误,名词。forEach不是函数

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两种方法,但是都没有成功,也许我错过了一些东西,或者有些东西我只是不明白为什么我无法映射数据。

1 个答案:

答案 0 :(得分:4)

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