losing bound this in promise
mark-hahn opened this issue · comments
Mark Hahn commented
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?
Sindre Sorhus commented
You have to bind it before passing it to pify.
Mark Hahn commented
I tried that also. I'll try it again.
Francisco Giordano commented
The correct way to do this is
writeRaw(address, length, buffer) {
return pify(this.bus).i2cWrite(address, length, buffer)
}
Sindre Sorhus commented
Fixed by #69.