express-dynamic-middleware icon indicating copy to clipboard operation
express-dynamic-middleware copied to clipboard

async middlewares are skipped due to the usage of async.each()

Open Tuvalnik12 opened this issue 5 years ago • 2 comments

Hey man! Bumpped into your repo and it's exactly what I need! Amazing, thanks for that man. I recommend changing the function you are using in the handle() function from async.each to async.eachOfLimit() with a limit of 1 each time so middlewares run in the order the developer sets them in the array.

Tuvalnik12 avatar Dec 20 '20 12:12 Tuvalnik12

@Tuvalnik12 Hi, thanks for your approval. With your advice, do you mean send a param "index" of the array to the middleware function? I'm not quite sure what you mean. Or you can write a sample of code.

lanbomo avatar Dec 20 '20 13:12 lanbomo

I was trying to use an async function that resolves with a 400 res as the first function in the dynamic instance.

Due to the usage of async.each() the handle function runs all of the wares in parallel as mentioned in the async docs. https://caolan.github.io/async/v3/docs.html#each.

I recommend using async.eachOfLimit, so every ware runs according to the array order, like this: async.eachOfLimit(wares, 1, function(fn, callback) { fn(req, res, callback); }, function(err) { if (err) { return console.error(err); } next(); });

The end result is that I as a developer can run wares that resolve with a response and the rest of the wares don't run. I can stop the flow. Thanks for the response, I appreciate it very much.

Tuvalnik12 avatar Dec 20 '20 14:12 Tuvalnik12