Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

losing bound this in promise #63

Closed
mark-hahn opened this issue Aug 14, 2018 · 4 comments
Closed

losing bound this in promise #63

mark-hahn opened this issue Aug 14, 2018 · 4 comments

Comments

@mark-hahn
Copy link

mark-hahn commented Aug 14, 2018

My code is

  writeRaw(address, length, buffer) {
    return pify(this.bus.i2cWrite).bind(this.bus)(address, length, buffer)
  }

but when i2cWrite is called this is undefined. this is set when this runs

  ret[key] = typeof property === 'function' && filter(key) ? processFn(property, options) : property;

but not inside the called processFn function

const processFn = (fn, options) => function (...args) { 
  // 'this' is not set here
 <...>
}

What am I doing wrong?

P.S. Sorry I don't understand bind well enough to know what happens to a bound => function. I know => uses this from outside scope, but is that overridden by bind?

EDIT: I just realized that looking at this before and during processFn means nothing. I will try to debug this better but meanwhile, can someone look at my code above?

@sindresorhus
Copy link
Owner

You have to bind it before passing it to pify.

@mark-hahn
Copy link
Author

I tried that also. I'll try it again.

@frangio
Copy link
Contributor

frangio commented Jun 20, 2019

The correct way to do this is

writeRaw(address, length, buffer) {
    return pify(this.bus).i2cWrite(address, length, buffer)
}

@sindresorhus
Copy link
Owner

Fixed by #69.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants