Skip to content

Instantly share code, notes, and snippets.

@joaodasilva
Created February 13, 2022 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaodasilva/f5fe471c7b27a2606689c6aeeb7398ed to your computer and use it in GitHub Desktop.
Save joaodasilva/f5fe471c7b27a2606689c6aeeb7398ed to your computer and use it in GitHub Desktop.
function resolveAfterTimeout(millis) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, millis);
});
}
class ChildProcess {
constructor(child, index) {
this.child = child;
this.index = index;
child.addEventListener('exception', this.onException.bind(this));
child.addEventListener('exit', this.onExit.bind(this));
// child.addEventListener('message', this.onMessage.bind(this));
this.promise = new Promise((resolve) => { this.resolve = resolve; });
this.resolved = false;
}
async waitUntilDone() {
try {
await Promise.race([ this.promise, resolveAfterTimeout(10 * 1000) ]);
} finally {
this.child.close();
if (!this.resolved) {
console.log('-- TIMED OUT');
Process.exit(1);
}
}
}
onException(event) {
const trace = event.stacktrace || [];
console.log('-- EXCEPTION: ' + event.message + '\n' + trace.join('\n'));
Process.exit(1);
if (!this.resolved) {
this.resolved = true;
this.resolve();
}
}
onExit(event) {
if (event.status != 123) {
console.log('-- FAIL EXIT: ' + event.status + ', ' + event.error);
Process.exit(1);
} else {
console.log('-- child ' + this.index + ' done');
}
if (!this.resolved) {
this.resolved = true;
this.resolve();
}
}
}
async function test() {
const options = {
log : true,
};
let children = [];
let pending = [];
for (let i = 0; i < 100; i++) {
const process = Process.spawn('child.js', [], options);
const child = new ChildProcess(process, i);
child.xx = child.waitUntilDone();
children.push(child);
pending.push(child.xx);
if (pending.length >= 20) {
await Promise.race(pending);
pending = children.filter(x => !x.resolved).map(x => x.xx);
console.log('-- pending after waiting: ' + pending.length);
}
}
await Promise.all(pending);
Process.exit(0);
}
window.visible = false;
test();
// also create child.js with a single line:
//
// Process.exit(123);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment