Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

nodejs middleware delaying requests

nodejs middleware delaying requests

Problem

I'm writing a middleware which will perform a sequence of actions. After the sequence is done, I want the middleware to call next(). from this point on the middleware is redundant. I've written the following code: (here the sequence of actions is mocked by a call to setTimeout):

function myMiddleware(req, res, next){

   console.info("inside myMiddleware");

   if (actionDone) {
       console.info("middleware redundant. ActionDone, calling next");
       next();
   }

   setTimeout(doneWaiting, 30000);

   function doneWaiting(){
      actionDone = true;
      next();
   }
}

This code will not work because if more than one request arrives before the action is done, setTimeout will be called again and again. I want setTimeout to be called only once, and only when it's done I want to call next() on all the requests which arrived so far.

What is the best way to achieve this?

Thanks, Li

Problem courtesy of: user429400

Solution

If I understand correctly you want to perform a task and handle all requests once the task is finished? Until that happens they wait?

So here's non scalable way:

var EventManager = new require("events").EventEmitter( );
var actionDone = "start";

function myMiddleware(req, res, next){

   console.info("inside myMiddleware");
   var handler = function( ) {
       console.info("middleware redundant. ActionDone, calling next");
       next();
   };

   if (actionDone === "finished" ) {
       handler( );
       return;
   }

   EventManager.once( "finished", handler );

   if (actionDone !== "working") {
       actionDone = "working";
       function doneWaiting(){
          actionDone = "finished";
          EventManager.trigger( "finished" );
       }
       setTimeout(doneWaiting, 30000);
   }
}

Obviously it is not scalable, because you cannot share EventManager object between machines. In order to do that between machines you would probably have to fire requests from the main server to every other server and handle the request similarly.

WARNING: what you trying to do looks like a very very bad idea. After all requests should not depend on each other. This can easily lead to server crash.

Solution courtesy of: freakish

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

nodejs middleware delaying requests

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×