Last active
January 2, 2016 15:38
-
-
Save smitelli/8324403 to your computer and use it in GitHub Desktop.
Weirdness with Lodash's _.bind and Superagent callbacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var lodash = require('lodash'), | |
request = require('superagent'), | |
TestObj = {}; | |
function asyncRequest (callback) { | |
callback(null, {status : 'It works!'}); | |
} | |
TestObj.foobar = 'bazquux'; | |
TestObj.doFakeRequest = function () { | |
asyncRequest(lodash.bind(function (err, res) { | |
console.log('Errors', err); | |
console.log('Status', res.status); | |
console.log('FooBar', this.foobar); | |
}, this)); | |
}; | |
TestObj.doSuperagentRequest = function () { | |
request.get('http://example.com').end(lodash.bind(function (err, res) { | |
console.log('Errors', err); | |
console.log('Status', res.status); | |
console.log('FooBar', this.foobar); | |
}, this)); | |
}; | |
TestObj.doFakeRequest(); | |
/* | |
Errors null | |
Status It works! | |
FooBar bazquux | |
*/ | |
TestObj.doSuperagentRequest(); | |
/* | |
Errors { ...contents of `res`... } | |
./test.js:24 | |
console.log('Status', res.status); | |
^ | |
TypeError: Cannot read property 'status' of undefined | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment