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.