Understanding process.nextTick() - How To Node - NodeJS
Understanding process.nextTick() - How To Node - NodeJS
However, process.nextTick() is not just a simple alias to setTimeout(fn, 0) - it's far more efficient. More precisely, process.nextTick() defers the function until a completely new stack. You can call as many functions as you want in the current stack. The function that called nextTick has to return, as well as its parent, all the way up to the root of the stack. Then when the event loop is looking for a new event to execute, your nextTick'ed function will be there in the event queue and execute on a whole new stack. Interleaving execution of a CPU intensive task with other events Let's say we have a task compute() which needs to run almost continuously, and does some CPU intensive calculations. If we wanted to also handle other events, like serving HTTP requests in the same Node process, we can use process.nextTick() to interleave the execution of compute() with the processing of requests this way:var http = require('http'); function compute() { // performs complicated calculations continuously // ... process.nextTick(compute); } http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World'); }).listen(5000, '127.0.0.1'); compute();
沒有留言:
張貼留言