![](/img/trans.png)
[英]What are the proper use cases for process.nextTick in Node.js?
[英]Node.js process.nextTick still blocking server from getting requests
我得到了這段代碼:
import http from 'http'; function compute() { let [sum, i] = [1, 1]; while (i<1000000000) { 5*2 i++; } console.log("good"); process.nextTick(compute); } http.createServer((request, response) => { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World'); }).listen(5000, '127.0.0.1'); http.request({hostname: '127.0.0.1', port: 5000}, (response) => { console.log("here !"); }).end(); compute();
該輸出始終是:“好”,“好” ...並且未調用HTTP請求。我認為process.nextTick應該可以解決該問題,但是服務器仍然被阻止。 ?
代替process.nextTick
而是使用set setImmediate
。 傳遞給nextTick
回調將在IO回調之前進行處理,而傳遞給setImmediate
回調將在已處理的回調之后進行處理。
替換process.nextTick(compute);
與setImmediate(compute);
。
也可以將CPU工作移至子進程或工作進程。 但我不會描述這一點,因為我的主要觀點是解釋如何:
function compute() {
...
console.log("good");
process.nextTick(compute);
}
會阻塞HTTP服務器處理請求, while
忽略while
循環,這有其自身的問題。
有關更多信息,請參見setImmediate與nextTick 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.