H
H
HoHsi2016-02-18 19:27:06
JavaScript
HoHsi, 2016-02-18 19:27:06

Should I use setImmediate / nextTick in Express?

Good afternoon!
Recently wondered if it's worth using setImmediatein Express?
Those. does it make sense to write middleware and routers like this:

app.use((req, res, next) => {
  setImmediate(() => {
    // Тяжелая синхронная операция
    ultraMegaLongComputing();
    next();
  });
})

instead of the standard one:
app.use((req, res, next) => {
  // Тяжелая синхронная операция
  ultraMegaLongComputing();
  next();
})

And in general, what are the use cases for setImmediate / nextTick in Node.js, and in client JS as well?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2016-02-18
@bingo347

Simply wrapping a heavy operation in setImmediate will not give you much profit, you still block the thread for the duration of its execution.
But you can break it into small quick parts using setImmediate, midleware itself will work a little slower, but EventLoop will work.
In most cases, it is adequate to interrupt the EventLoop processing task every 1000 iterations of the loop, although the specific number of iterations depends on the computational complexity of the loop body in your case.

I
Ivan, 2016-02-18
@LiguidCool

I'm not a node guru at all, but in my opinion the 1st is pointless ... And how to return res? After all, your program will "run further" with an empty res and nothing will be returned to the browser. Maybe for recording information and requesting it separately after that it is somehow applicable ...
In any case, what prevents you from checking?
PS
I'm an amateur and don't listen to me :)
Correct me if I'm wrong.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question