简体   繁体   English

如何构建此服务器后端路由?

[英]How can I construct this server backend route?

I'm working on a fullstack project where I need a way to effectuate the following scenario:我正在做一个全栈项目,我需要一种方法来实现以下场景:

Upon a user submit event:在用户提交事件时:

  1. A request is posted to the backend一个请求被发布到后端
  2. When the server receives the req., it begins executing some function当服务器收到请求时,它开始执行一些 function
  3. The backend should run said function on a loop/indefinitely until the backend receives a subsequent request which instructs the server to cease executing the function after the function completes its current iteration.后端应循环/无限期地运行所述 function,直到后端收到后续请求,该请求指示服务器在 function 完成其当前迭代后停止执行 function。

I know there must be a way to work this out, but I haven't been able to figure out how to condense my problem/question into something I can google search my way through.我知道一定有办法解决这个问题,但我一直无法弄清楚如何将我的问题/问题浓缩成我可以通过谷歌搜索的东西。

The following will hopefully help to convey what I'm trying to accomplish:以下内容有望帮助传达我要完成的工作:

let run_function = false;

app.post('/start', (req, res) => {
  run_function = true;
  while (run_function)
    the_function(req.body);
}

app.get('/stop', (req, res) => {
  run_function = false;
}

Seems like a job for setInterval() / clearInterval()似乎是setInterval() / clearInterval()的工作

let handle

// Default 200ms interval
const startLoop = (body, interval = 200) => {
  clearInterval(handle) // stop any previous loops
  handle = setInterval(the_function, interval, body)
}

app.post("/start", (req, res) => {
  startLoop(req.body)
  res.send("Started")
})

app.post("/stop", (req, res) => {
  clearInterval(handle)
  res.send("Stopped")
})
let LoopInterval = null; app.post('/start', (req, res) => { LoopInterval = setInterval(() => { the_function(req.body); }, 0); }); app.get('/stop', (req, res) => { clearInterval(LoopInterval) });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM