【发布时间】:2015-11-05 11:48:31
【问题描述】:
我最近开始研究 JS 和 Node.js。但是我并不完全喜欢编写回调风格的代码,所以我开始为 Node.js 编写一个小框架。我已经完成了它,但现在我正试图让它在节点集群的多核上工作。问题是,我不能将生成器从主服务器发送给工作人员,因为我的框架是基于生成器的,我必须让工作人员运行生成器。我如何将生成器对象转换为 JSON,然后我可以将其发送给我的工作人员或将生成器发送给工作人员的其他方法?我尝试将生成器转换为 JSON,但结果是一个没有 next 或 throw 方法的空对象。
以下是乒乓球的示例:
Thr.setNumCPUs(require("os").CPUS.length-1)
//not to have one extra because of the master
function ping(times){
var chan = new Thr.Chan();//create new channel
Thr.spwn(function* (){//start a new thr, on any of the cpus
var chan2 = pong(chan);
for (var i= 0;i < times;i++){
yield* chan.send("ping, for the "+(i+1)+" timth");
//wait untill chan is empty, then send a value
console.log(yield* chan2.rcv());
//wait until received the value
}
chan.close();
//close the channel so now on can access it
} ,[]);
}
function pong(chan){
var chan2 = new Thr.Chan();
Thr.spwn(function* (){
var i = 0;
while (!chan.closed){
console.log(yield* chan.rcv());
yield* chan2.send("pong, for the "+(++i)+" timth");
}
chan2.close();
} ,[]);
return chan2;
}
if (cluster.isMaster){
ping(5);
}
【问题讨论】:
-
原生 JSON 解析器无法评估 JSON 中的函数,它们无效。
-
我知道,但是,有没有另一种方法来解析它,或者以不同的方式将结果发送给工作人员。我什至无法将函数 *.next 放到字符串中。
-
您必须实现自己的 JSON 解析器 (!)
-
好吧,我可能没有时间这样做,我什至无法将 generator.next 放到一个字符串中。
-
当您尝试将函数转换为字符串时会发生什么。似乎对我有用。
标签: javascript json node.js generator