javascript - 如何等待父进程发送数据?
问题描述
我是使用 fork 的新手,我想知道
是否有办法等待父进程将数据发送到子进程?
也许是这样的
index.js:
var fork = require('child_process').fork;
var child = fork(__dirname + '/index 2.js');
child.on('message', function (response) {
console.log(response);
});
async function out(){
child.send(50);
await new Promise(r => setTimeout(r, 3000)); //sleeps for 3000ms
child.send(30);
}
out();
index2.js:
let a=0;
function wait_and_listen(){
let temp_data;
process.on('message',(data)=>{temp_data=data});
return temp_data;
}
a+=wait_and_listen();
a-=wait_and_listen();
process.send(a);
process.exit();
解决方案
您只需使用一次“process.on('message') 并计算其调用次数。
// variable to detect if its the first call
let nthcall = 0;
// variable to accumulate data
let a = 0;
// work functon to be called when data is received from the parent
function work(data) {
nthcall++;
// feel free to do wwhatever you like with your data depending on nthcall value
a += data;
if (nthcall == 1) {
console.log('first time i got data', data);
return;
}
if (nthcall == 4) {
console.log('last time i got data', data);
process.send(a);
process.exit(0);
}
console.log('i got data', data);
}
process.on('message', work);
推荐阅读
- linux - 为什么我在多个终端上同时运行相同的 Python 脚本时不会出错?
- xlsxwriter - xlsxwriter:如何更改单个 add_series() 的散点图子类型?
- laravel - 我正在使用 Bootstrap 和 Tailwind CSS 开发 Laravel。我的tailwindcss没有被选中
- c++ - C++/Qt Valgrind 未初始化字节
- ios - Xamarin 窗体 iOS 应用相同的字体但不同的样式
- ios - 如何从模态视图重新加载后台 UITableView
- java - Java 异常 getMessage() 返回 null
- sql - IS Insert Select FROM CTP 一个原子事务
- javascript - JavaScript 错误 $.param.querystring 不是函数
- algorithm - 计算大指数份额/概率