首页 > 解决方案 > 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.

标签: javascriptjavarest

解决方案


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

推荐阅读