Skip to content

Instantly share code, notes, and snippets.

@smitelli
Last active January 2, 2016 15:38
Show Gist options
  • Save smitelli/8324403 to your computer and use it in GitHub Desktop.
Save smitelli/8324403 to your computer and use it in GitHub Desktop.
Weirdness with Lodash's _.bind and Superagent callbacks
'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