1

I have this function.

function runInDomain(func) {                               
  const d = domain.create();                               
  d.on('error', (er) => {                                  
    console.log(`error on: ${func.name}`, er, er.stack);   
    // just ignore                                         
  });                                                      
  console.log(`run in domain: ${func.name}`);              

  d.run(func);                                             
}  

And run it with this,

function bar() {       
  console.log('bar');  
  throw false;         
}                 

setInterval(() => { runInDomain(bar) }, 1000); // 'bar' runs only one time.

function 'bar' runs only one time:

$ node test.js 
run in domain: bar
bar
error on: bar false undefined

but with this,

setInterval(() => { setImmediate(() => { runInDomain(bar) }) }, 1000); // it works!

It works fine:

$ node test.js 
run in domain: bar
bar
error on: bar false undefined
run in domain: bar
bar
error on: bar false undefined
run in domain: bar
bar
error on: bar false undefined
....

I don't know why the first thing doesn't work but the second one does. Any reason?

ljh131
  • 113
  • 10

1 Answers1

0

I didn't see anything wrong with your code. I do the same thing and here, works fine:

var domain = require('domain');
var fs = require('fs');

var runInDomain = function(func) {
    var d = domain.create();

    d.on('error', function(err) {
      console.log(`error on: ${func.name}`);
    });

    d.run(func);
}

// any bar method
var bar = function() {
    fs.readFile('somefile.txt', function (err, data) {
        if (err) throw err;
        console.log(data);
    });
}

setInterval(() => {
    runInDomain(bar)
}, 1000);

I hope it helps.

Celso Agra
  • 1,389
  • 2
  • 15
  • 37
  • Also, I found a [post](http://stackoverflow.com/a/7313005/2130322) that can be useful for you – Celso Agra Jan 03 '17 at 03:39
  • your code works fine too me. (it means, runs forever), why don't you try this, instead of yours? var bar = function() { throw false; } – ljh131 Jan 03 '17 at 04:14