So I've got this JS code here, and I'm trying to set obj from the success and error callbacks, but apparently the toLinkInfo
function scope is not a parent scope of those? I always get null back from this function no matter what. I tried a bunch of stuff but couldn't get it to work, I guess I'm too used to C & friends :) How can I get this to work?
LinkInfoGrabber.prototype.toLinkInfo = function() {
var obj = null;
$.ajax({
url: this.getRequestUrl(),
success: function(raw) {
obj = new LinkInfo(raw);
},
error: function(jqXHR, textStatus, errorThrown) {
obj = new LinkInfoException(jqXHR, textStatus, errorThrown);
},
dataType: 'html'
});
if (obj instanceof LinkInfo) {
return obj;
} else {
throw obj;
}
}
That's because AJAX calls are asynchronous -- they happen at a different time from the rest of the context.
Try giving it a callback function( called callback below ).
LinkInfoGrabber.prototype.toLinkInfo = function(callback) {
$.ajax({
url: this.getRequestUrl(),
success: function(raw) {
callback( new LinkInfo(raw) );
},
error: function(jqXHR, textStatus, errorThrown) {
obj = new LinkInfoException(jqXHR, textStatus, errorThrown);
},
dataType: 'html'
});
}
var l = new LinkInfoGrabber()
l.toLinkInfo(console.log) //replace console.log with something meaningful
While this approach does not provide exactly the same result as being able to call everything inline, it has the benefit of allowing for the asynchronous nature of the web.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With