Home > Enterprise >  execute next request once the execution of first request is completed in node
execute next request once the execution of first request is completed in node

Time:04-30

Let's assume I have an endpoint /print. Whenever a request is made to this endpoint, it executes a function printSomething(). While printSomething() is processing, if the user or another user hits this endpoint it will execute printSomething() again. If this occurs multiple times the method will be executed multiple times in parallel.

app.get('/print', (req, res) => {
  printSomething(someArguments);
  res.send('processing receipts');
});

The issue with the default behavior is that, inside printSomething() I create some local files which are needed during the execution of printSomething() and when another call is made to the printSomething() it will override those files, hence none of the call's return the desired result.

What I want to do is to make sure printSomething() execution is completed, before another execution of printSomething() is started. or to stop the current execution of printSomething() once a new request is made to the endpoint.

CodePudding user response:

You have different option based on what you need, how much request you expect to receive and what you do with those file you are creating

Solution 1

If you expect little traffic on this endpoint

you can add some unique key to someArguments based on your req or randomly generated and create the files you need in a different directory

Solution 2

If you think that it will cause some performance issue you have to create some sort of queue and worker to handle the tasks.

In this way you can handle how many task can be executed simultaneously

CodePudding user response:

You could use app.locals, as the docs suggest: Once set, the value of app.locals properties persist throughout the life of the application.

You need to use req.app.locals, something like

req.app.locals.isPrinting = true;
----
//Then check it
if (req.app.locals.isPrinting)

req.app.locals is the way express helps you access app.locals

  • Related