I'm new to using forks and I was wondering
if there is a way to wait for the parent process to send data to the child process?
maybe something like this
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();
You could use promise in your child script to await for the parent to send data
not sure but maybe something like this:
let a = 0;
async function wait_and_listen() {
return await new Promise((resolve) =>{
process.on('message', (data) => { resolve(data); });
});
}
(async()=>{
a += await wait_and_listen();
a -= await wait_and_listen();
process.send(a);
process.exit();
})();
Edit:
according to OP the above solution creates multiple listeners so in order to avoid that use .once instead of .on like this:
let a = 0;
async function wait_and_listen() {
return await new Promise((resolve) =>{
process.once('message', (data) => { resolve(data); });
});
}
(async()=>{
a += await wait_and_listen();
a -= await wait_and_listen();
process.send(a);
process.exit();
})();
you just use the "process.on('message') once and count its' calls.
// 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);