Skip to content

async_hooks: context loss when awaiting a thenable #27599

@Qard

Description

@Qard

It seems async_hooks is losing context, in certain cases, when awaiting a thenable. This appears to occur in all major versions of Node.js with async_hooks available. See the code example and output for reference.

Within the then function on the thenable object, the trigger id is 0. Note that this does not happen when awaiting a thenable as the first await within an async function.

cc @nodejs/diagnostics

Code example
const async_hooks = require('async_hooks')

const asyncHook = async_hooks.createHook({
  init (asyncId, type, triggerAsyncId) {
    log({
      event: 'init',
      asyncId,
      type,
      triggerAsyncId
    })
  },

  before (asyncId) {
    log({
      event: 'before',
      asyncId
    })
  },

  after (asyncId) {
    log({
      event: 'after',
      asyncId
    })
  }
})
asyncHook.enable()

function log (data) {
  process._rawDebug(JSON.stringify(data))
}

function tick () {
  return new Promise(setImmediate)
}

async function main () {
  await tick()
  await {
    then (fn) {
      log({
        executionAsyncId: async_hooks.executionAsyncId(),
        triggerAsyncId: async_hooks.triggerAsyncId(),
        message: 'these ids should not be zero'
      })
      setImmediate(fn)
    }
  }
}

main()
Output
{"event":"init","asyncId":2,"type":"PROMISE","triggerAsyncId":1}
{"event":"init","asyncId":3,"type":"PROMISE","triggerAsyncId":1}
{"event":"init","asyncId":4,"type":"Immediate","triggerAsyncId":1}
{"event":"init","asyncId":5,"type":"PROMISE","triggerAsyncId":3}
{"event":"before","asyncId":4}
{"event":"after","asyncId":4}
{"event":"before","asyncId":5}
{"event":"init","asyncId":6,"type":"PROMISE","triggerAsyncId":2}
{"event":"init","asyncId":7,"type":"PROMISE","triggerAsyncId":6}
{"event":"after","asyncId":5}
{"executionAsyncId":0,"triggerAsyncId":0,"message":"these ids should not be zero"}
{"event":"init","asyncId":8,"type":"Immediate","triggerAsyncId":0}
{"event":"before","asyncId":8}
{"event":"after","asyncId":8}
{"event":"before","asyncId":7}
{"event":"after","asyncId":7}

Metadata

Metadata

Assignees

No one assigned

    Labels

    async_hooksIssues and PRs related to the async hooks subsystem.feature requestIssues that request new features to be added to Node.js.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions