Skip to content

AsyncResource.bind always alters the value of this unexpectedly #42158

Closed
@rochdev

Description

Version

17.6.0

Platform

No response

Subsystem

No response

What steps will reproduce the bug?

const fn = AsyncResource.bind(function () {
  console.log(this)
})

fn.apply('foo') // will log the AsyncResource instead of 'foo'

const obj = { fn }

obj.fn() // will log the AsyncResource instead of `obj`

How often does it reproduce? Is there a required condition?

Always as the code is explicitly binding thisArg even when not provided.

What is the expected behavior?

AsyncResource.bind should use the this value provided by the caller by default and only bind this when a thisArg is passed explicitly.

What do you see instead?

AsyncResource.bind defaults to setting this to itself, which is not only unexpected in pretty much all cases, but also makes it impossible to use the this provided by the caller without an explicit reference to the caller at bind time. This means that in all situations right now it would make more sense to use runInAsyncScope instead of bind making it effectively unusable.

Additional information

As an APM vendor, we're making heavy use of this API and there is not a single occurrence in our code where the default works.

The feature was originally implemented in #36782

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    async_hooksIssues and PRs related to the async hooks subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions