"Lost in the mist of the unfulfilled promise

As a newcomer to JavaScript, I recently came across a text document filled with nouns and thought it would be a great idea to create an API using these words.

I parsed the file and stored the nouns in 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;
}

I then converted this list to Json using 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();
}

Next, I started working on the frontend using JS and attempted to fetch the data. However, I encountered an error stating "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 have tried using both map and forEach methods without success. It seems like there might be something missing or a misunderstanding on my part regarding why I am unable to map the data.

Answer №1

If you're looking to achieve what you want, you should use the map method instead of forEach. The forEach method does not return a value; it simply iterates over the collection.

The error message you're receiving stating "is not a function" is likely due to the missing function call on res.json. It should be written as 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("");
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript implementation of Twitter OAuth authentication

I searched far and wide for a strong example of a JQuery ajax call to authenticate a user on Twitter using their OAuth method. I carefully followed the instructions multiple times and this is what I've managed to put together so far. Currently, I am f ...

If the entity directory is not specified in the configuration files, TypeORM will be unable to locate the entities

I am currently utilizing TypeORM with the following setup in my ormconfig.json file: { "type": "mysql", "host": "localhost", "port": 3306, "username": "root", "password": "my-secret-pw", "database": "mytestdb", } All of my Entity files are saved in the d ...

What is preventing me from running my alert script in JavaScript?

Need some assistance here. I have a simple question. I am trying to create an alert function using JavaScript, but it is not working. <script type="text/javascript"> $(".delete").click(function(){ alert("Are you sure?&q ...

Scaling down the screen for a smaller display

Having trouble achieving a specific effect and could use some assistance. My goal is to create an action where, upon clicking on the nav element (for simplicity, I've set it to be triggered by clicking anywhere on the body), the following should occur ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

Ways to organize an array based on various characteristics

I am seeking assistance regarding grouping in Javascript. Below is an array where each item has either is_sweet, is_spicy, or is_bitter set to true: const foodsData = [{ name: 'mie aceh', is_sweet: false, is_spicy: true, ...

What methods can be used to have parse-server recognize that ESM is being utilized?

I am currently in the process of transitioning from CommonJS to ESM in my Node.js server, specifically for running ParseServer version 6.4.0. I have made the necessary adjustments to my code, however, ParseServer is unable to detect that I am now using ECM ...

Utilizing the existing Choco solver model for additional solution constraints

I am currently utilizing the choco solver library to create a series of puzzles. My goal is to run the solver, determine the number of solutions available, and if there is more than one solution, implement an additional constraint. By repeating this proces ...

Whenever isEmailVerified() returns false, even after the email has been verified

When a user logs into their account, the system checks if they have verified their email address. If not, the EmailVerificationActivity is initiated. Upon clicking the SEND VERIFICATION EMAIL Button, a verification code is sent to the user's email add ...

Incorporate Ruby's embedded helpers with jQuery for advanced functionality

How do I properly add a ruby helper to iterate through an active record response? I attempted to do so with the following code (.html or .append): $( ".result" ).html('<%= @products.each do |product| %><label>product</label><% e ...

Mastering the implementation of owl-carousel in React.js

I'm currently working on a project that involves utilizing the react framework. My intention is to incorporate the owl-carousel, however, I've encountered issues as it fails to function properly. The following error keeps popping up: OwlCarousel ...

How can I dynamically insert HTML content into a data-attribute using JavaScript?

I have been trying to insert a variable that includes HTML code into a DATA attribute (a href ... data-content= ...), but it isn't functioning properly. The code I input seems to delete certain characters and as a result, it does not display correctly ...

Is there an equivalent in Struts2 for checking if there are more action errors using actionError

Can you tell me the Struts2 equivalent of this line from an action class: if(actionError.get("myError").hasNext()){ .... } ...

Assigning a byte value to a field within an object

I have a program with the following code: class SerializeBox implements Serializable { private byte serializableProperty = 10; public byte getSerializableProperty() { return serializableProperty; } public void setSerializabl ...

Managing the css @print feature within the WordPress admin interface

When attempting to use 'window.print()' to print only a specific div inside the WordPress admin area, I tried enqueueing CSS to load on the desired page and hide all elements except for the target div. However, the issue arises when the text form ...

Eliminate specific elements from an array while retaining others

Here is a simple page setup: https://i.sstatic.net/z9MF9.png The page consists of an input field at the top, followed by a list (<ul>), and a button for saving changes. The <ul> is connected to an array called items. When the user clicks on "S ...

React-native horizontal sliding plugin

Can anyone recommend a reliable horizontal slider plugin for react-native? I've come across some options, but they haven't been working as smoothly as I'd hoped. ...

Understanding the significance of the argument in the context of `express.json({ extended: false})`

Currently, I am in the process of setting up an API using express and encountered this particular line of code: app.use(express.json( { extended: false } )); Although I have referred to the documentation provided by express, I was unable to locate this sp ...

The Add/Remove button functionality is not functioning as expected for duplicated form fields when using jQuery

I am experiencing an issue with the functionality of the "Add another" and "Remove row" buttons in my form. I implemented code from a specific Stack Overflow answer (jquery clone form fields and increment id) to create a cloneable section, but only the ori ...

Can date ranges be utilized as separate date items on the time scale in D3.js?

I have a chart that resembles the one shown below, however, there is a crucial component missing. Currently, my time scale follows the standard format as depicted in the first picture. I am looking to convert it to the time scale seen in the second picture ...