Skip to content

Binding context to promise chain #498

@maxbrieiev

Description

@maxbrieiev

Hi!

I want to bind some context to promise chain for the purpose of context aware logging. For this my idea is to extend promise API. Here is an example:

const when = require('when');

let getUserSession = when('get user session');
when()
  .bindToCtx({taskId: 123})
  .then(function () {
    return getUserSession.log('Got session');
  })
  .then(function (session) {
    return when('get some data from db')
      .log('Got data from DB')
      .then(function (data) {});
  })
  .log('task finished');

I would expect to see something like this in the log output:

debug:task:123: Got session 
debug:task:123: Got data from DB
debug:task:123: task finished

My idea was to extend Promise along following lines:

const when = require('when');

function contextLogging(Promise) {
  Promise.createContext = function(p, context) {};
  Promise.enterContext = function (p) {};
  Promise.exitContext = function () {};

  Promise.prototype.bindToCtx = function (ctx) {};
  Promise.prototype.log = function (msg) {};

  return Promise;
}

At first I thought that when/monitor/PromiseMonitor would be a good start. But after playing with it for some time, I am a bit confused. To me it appears that it doesn't track context properly. Here is an example:

require('when/monitor/console');
var when = require('when');

var p1 = when(1);
var p2 = when(2);

p1.then(function f1() {
  return p2
    .then(function f2() {
      return 3;
    })
    .then(function f3() {
      doh();
    });
});

Here I expect that p2 runs within the context of p1. However, the traceback doesn't give any insights on this:

% node test.js
[promises] Unhandled rejections: 1
ReferenceError: doh is not defined
    at f3 (/home/mbreev/test.js:13:7)
from execution context:
    at run (bootstrap_node.js:427:7)
from execution context:
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
from execution context:
    at Object.<anonymous> (/home/mbreev/test.js:5:10)

So my question is: would PromiseMonitor be a good example to implement context binding to chain of promises?

Is it feasible at all to extend Promise this way?

Thank you in advance for any suggestions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions