sindresorhus / pify

Promisify a callback-style function

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

losing bound this in promise

mark-hahn opened this issue · comments

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?

You have to bind it before passing it to pify.

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

The correct way to do this is

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

Fixed by #69.