3

I create domain and run it. Now while domain is entered process.domain points to current active domain. But then I run Promise and get something strange.

'use strict';

var domainCreate = require('domain').create;

var domain = domainCreate();
domain.requestId = 1;
domain.run(function() {
    console.log(process.domain === domain); // true
    console.log(process.domain.requestId); // 1
    Promise.resolve().then(function() {
        console.log(process.domain === domain); // false!!!
        console.log(process.domain.requestId); // throw new TypeError('Cannot read property 'requestId' of undefined')
    }).catch(function(err) {
        console.error(err.stack);
    });
});

Why process.domain becomes undefined inside Promise chain?

happy_marmoset
  • 2,137
  • 3
  • 20
  • 25

2 Answers2

6

Native promises and domains don't mix. There's an issue here where it's mentioned (here) that:

I haven't looked too deeply into now V8's native promises are implemented, but it would not surprise me if it turned out to be necessary to patch them to work with domains.

And the latest comment in that thread (here) suggests that this is still an issue with Node v6 (which it is).

One of the comments to the issue suggests that using a third-party promises implementation like bluebird may work better (your example code will work with it), but given that domains are considered to be a bit of a hack (and therefore have been deprecated), I think you should probably look at reimplementing your code without using domains at all.

robertklep
  • 198,204
  • 35
  • 394
  • 381
0

According to Node.js documentation module "domain" is deprecated with stability level 0. Better handle errors in another way https://nodejs.org/api/domain.html