callback-hell icon indicating copy to clipboard operation
callback-hell copied to clipboard

Callback binding

Open mappum opened this issue 9 years ago • 1 comments

Maybe it would be useful to mention callback binding, I know that personally was confusing for me in the beginning. For instance, you might expect this to work:

Something.prototype.foo = function (cb) {
  someOtherObj.bar(function (err, res) {
    cb(null, this.value)
  })
}

But actually it will not work since the innermost callback is called from the context of someOtherObj, and this doesn't resolve to the Something instance (so this.value end up being something else).

The solutions are foo(function () { this.value... }.bind(this)), var self = this; foo(function () { self.value... }), or maybe ES6 arrow functions (since they take their context from wherever they were created), () => { this.value... }.

mappum avatar Feb 16 '16 00:02 mappum

Oh yea good idea. Ill leave this open for the next time I'm doing work on this

max-mapper avatar Feb 16 '16 19:02 max-mapper