promise exhibiting inexplicable looping behavior

Here is the script that I am working with:

const got = require("got");
const getStream = require("get-stream");
const app = require("express")();

async function fetchData() {
  console.log("fetching response");
  let targetUrl = "http://localhost:3000/api";
  let gotOptions = {
    method: "get",
    headers: { "content-type": "application/json" },
    body: undefined,
    retries: 0
  };
  let response = await new Promise(async (resolve, reject) => {
    let stream = got.stream(targetUrl, gotOptions);
    stream.on("error", async error => {
      try {
        resolve(stream);
      } catch (err) {
        reject(err);
      }
    });
    stream.on("response", async res => {
      try {
        resolve(await getStream(res));
      } catch (err) {
        reject(err);
      }
    })
  });
  return response;
}

async function handleAPICalls(req, res, next) {
  try {
    const result = await fetchData();
    console.log(result);
  } catch (e) {
    throw new Error("an error occurred");
  }
  next();
}

app.use("/", [handleAPICalls]);

app.get("/api", (req, res) => {
  res.json({ data: "some output" });
});
app.get("/someapp", (req, res) => {
  res.end();
});

app.listen(3000, () => {
  console.log("server listening on port 3000");
});

Upon visiting "localhost:3000/someapp", the console will display

fetching response
fetching response
fetching response
fetching response
fetching response
fetching response
fetching response
fetching response
fetching response
fetching response
fetching response
...

During debugging, the promise consistently throws me back to the beginning of fetchData(), leaving me puzzled as to what the issue might be.

Answer №1

What's happening here?

You have set up the apiMiddleware to handle all routes, including the /api route. This means that every time a request is made to the server, apiMiddleware() is triggered, causing it to make an HTTP request to http://localhost:3000/api. This results in an endless loop. Additionally, since you are waiting for a response before sending a response, you may also run into memory issues due to quickly depleting resources.

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

Unraveling the process of webpack chunk generation for dynamic routing in React: A comprehensive guide

I am looking to organize my react javascript source code by breaking it into smaller chunk files for dynamic routing purposes. To gain insight into how dynamic routing functions, I decided to clone the react-router source code from https://github.com/Reac ...

Steps to drag, drop, and maintain the element's position for a period of time with JavaScript

I have been working on automating my Salesforce application using Selenium and incorporating JavaScript for drag and drop functionality. However, I am facing an issue where the element I drop onto the target ends up being positioned elsewhere. Manually hol ...

trouble seeing images with an array input and ngFor in Angular

I am encountering issues while attempting to exhibit an array of images by their source link using ngFor. It seems like there are errors hindering the functionality! Below is the image HTML code located within my card component: <div class="Session-Pa ...

The process of retrieving data from an MS SQL table through JSON web services in ASP.NET and then showcasing it in a jQuery datatable is currently experiencing issues on a live intranet

This is a snippet of code for my web services to list VIPs. public void GetVIPList() { List<Class_VIPlist> VIPNAME = new List<Class_VIPlist>(); using (SqlConnection sqlConn = new SqlConnection(System.Configuration.Configura ...

Developing object in place of an array (JavaScript)

After receiving data from the back-end, I handle it within a function: getAgentSuggestionById(agentId) { this._agentsService.getAgentSuggestionById(agentId).subscribe(result =>{ this.agent = result.items.map(e => {let obj = {name: e.name ...

Can you explain the significance of module.exports? And what is the reasoning behind naming it "module"?

I have another question in regards to learning express as a beginner. Can anyone recommend any helpful websites for someone new to this technology? I find that the official documentations can be quite unclear and overwhelming at times for beginners. Any ...

What is the best way to align text to the right in a Mui textfield in version 5?

How can I align the placeholder text to the right in Mui v5? I have tried using the sx property but it doesn't work. I'm not sure how to achieve this using the 'styled' method. https://i.sstatic.net/6gPD8.png Even after using inputProp ...

Modify the text style on the fly using React js

Looking to update the styling of the tab text in the navbar, as well as implement functionality where clicking on a tab switches between pages and marks the selected tab as active. Below is the code I've written: Header.js import React from "rea ...

emulate the activation of a hyperlink within a container

What is the most effective method, using either javascript or jquery, to create a simulated click on a live video within div id 1? I am unsure how to approach this situation when the <a> tag does not have an id attribute. <div id='1'&g ...

Unable to generate post in Prisma studio on nextjs. I encountered an error when attempting to save the post in Prisma studio in nextjs

I am experiencing difficulty in identifying the source of an error that is causing frustration. Why is Prisma studio unable to save the post in the database? I am utilizing a MongoDB cloud database, configured in my environment file. Here is the content o ...

Unable to add text to texarea using jquery

I recently discovered and am experimenting with smiley and uikit to create a feature that allows users to insert emoticons into a textarea. Here is the HTML structure: <textarea class="smiley-input uk-width-1-1"></textarea> <button type= ...

Unable to sign up for WordPress function

I'm having trouble getting my function registered properly in WordPress, no matter how many times I try. So far, here's what I've done: Inserted code into themes functions.php function test_my_script() { wp_register_script( 'custom-s ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

Arrange the computed item under a flexbox element

I am seeking guidance on a specific issue I am facing. My goal is to arrange multiple elements inside a flexbox in such a way that they can adapt to their environment. Underneath one of these items, I want to place a calculated element whose size will dep ...

Having trouble getting the Vue.js Element-UI dialog to function properly when embedded within a child component

Take a look at the main component: <template lang="pug"> .wrapper el-button(type="primary", @click="dialogAddUser = true") New User hr // Dialog: Add User add-edit-user(:dialog-visible.sync="dialogAddUser") </template> <s ...

JavaScript document string separation

Hi there, I'm a newbie here and could really use some assistance. I am struggling with creating a function and would appreciate any ideas... To give you an idea of what I need help with, I have a String and I want to check if it contains a specific w ...

Exploring the Interaction Between Node.js and a Windows 10 Server on a Local Machine

I am curious about the interaction between Nodejs Server and a local machine. Specifically, I would like to understand how tasks such as: Thread Level CPU Cycle Socket Level IO Any help in clarifying this process would be greatly appreciated. ...

The merging of $.each operations

Is it possible to combine multiple jQuery functions used to assign and change classes and IDs on elements into a single function rather than having separate functions for each? I am currently using the $.each function in jQuery. var stored = $.each; va ...

Looking to transform a PHP output value

I have a form with checkbox input, and a hidden 'sibling' input attached to it, in order to generate values of either '0' or '3' based on the checkbox status. When unchecked, the value is '0', and when checked, the ...

Encountered an error while trying to install Drivelist: Module 'C:Program Files odejs ode_modules pm ode_modules ode-gypin' not found

My electron project relies on the drivelist dependency. However, when I attempt to run "npm install," I encounter an error indicating that the node-gyp\bin folder is missing. Surprisingly, I do have the node-gyp\bin in my node modules and even in ...