如何在nodejs中添加数百万个数字而不阻止进一步执行?

时间:2016-07-08 06:53:04

标签: javascript node.js nonblocking

我正在尝试在节点js中实现问题的解决方案:

例如:

Ur是:http://localhost/sum/5

应该返回

" 1到5之间的数字总和是:15"

如果

网址:http://localhost/sum/100

答案应该是:

" 1到100之间的数字总和是:4950"

参数可能很大:

例如:

网址:http://localhost/sum/100000000 (一千万)

任何时候服务器都不应该只处理一个请求。

我在某地读过setImmediate可能有所帮助。

3 个答案:

答案 0 :(得分:1)

1 + 2 + 3 + ... + n的总和可用n(n + 1)/ 2表示。有关详细信息,请参阅this链接。

答案 1 :(得分:1)

通常,当您想要非阻塞执行时,可以使用child_process模块​​: https://nodejs.org/api/child_process.html

一个例子看起来像这样:

//fork a new process
var cp = require('child_process');
var child = cp.fork('./intensiveTask.js',[],{});

//listen for messages from the child process
child.on('message', function(ret) {
    console.log("child process has finished", ret.data);
    //kill the child process
    child.kill();
});

//send a message to the child process
child.send({msg: "Foo"});

以下是子进程的代码(intensiveTask.js)

process.on('message', function(data) {
    //do the intensive work here
    var output=data.msg + " Bar";
    //send the output back to the parent
    process.send({msg: output});

});

答案 2 :(得分:0)

我分享了一个可以帮助某人的代码段-

template

上面的代码片段仅添加了15000,然后返回结果作为响应。一切都由setImmediate方法管理。从这里了解更多信息-https://nodejs.org/api/timers.html