Skip to content

async_hooks.currentId() sometimes reports the wrong id during PromiseReactionJob #13427

Closed
@hayes

Description

@hayes
  • Version: v8.0.0
  • Platform: Wed Dec 31 14:42:53 PST 2014 x86_64 x86_64 x86_64 GNU/Linux
  • Subsystem: async_hooks

Sometimes async_hooks.currentId() returns the wrong id. as @AndreasMadsen pointed out here

The async_hooks.currentId() should just be the id from the latest before emit that hasn't been closed by the after emit.

Here is a simple example that shows this is not always working correctly with promises.

const async_hooks = require('async_hooks');
const fs = require('fs')

let indent = 0;
async_hooks.createHook({
  init(asyncId, type, triggerId, obj) {
    const cId = async_hooks.currentId();
    fs.writeSync(1, ' '.repeat(indent) +
                    `${type}(${asyncId}): trigger: ${triggerId} scope: ${cId}\n`);
  },
  before(asyncId) {
    fs.writeSync(1, ' '.repeat(indent) + `before:  ${asyncId}\n`);
    indent += 2;
  },
  after(asyncId) {
    indent -= 2;
    fs.writeSync(1, ' '.repeat(indent) + `after:   ${asyncId}\n`);
  },
  destroy(asyncId) {
    fs.writeSync(1, ' '.repeat(indent) + `destroy: ${asyncId}\n`);
  },
}).enable();

setTimeout(function () {
  Promise.resolve().then(() => {
    fs.writeSync(1, ' '.repeat(indent) + `current id in then: ${async_hooks.currentId()}\n`);
  })
})

which outputs:

Timeout(2): trigger: 1 scope: 1
TIMERWRAP(3): trigger: 1 scope: 1
before:  3
  before:  2
    PROMISE(4): trigger: 2 scope: 2
    PROMISE(5): trigger: 2 scope: 2
  after:   2
after:   3
before:  5
  current id in then: 0
after:   5
destroy: 2

Edited by @ChALkeR: mistype/spelling fix.

Metadata

Metadata

Assignees

No one assigned

    Labels

    async_hooksIssues and PRs related to the async hooks subsystem.promisesIssues and PRs related to ECMAScript promises.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions