I'm trying to create a globally accessible function that performs an ajax call:
function getDataModel(dataModelName = "dm1") {
// I want to send the deferred object back
return $.Defered($.get(url + dataModelName, function(r){
return new DataModel(r)
})
}
function DataModel(data){
this.foo = data.foo
this.bar = data.bar
}
I want to send the DataModel object to another function after it's created:
console.log("1");
// After the deferred object finishes being built, use it in another function,
// but that function can't be called till the object is built
$.when(getDataModel(fromSelection)).then(function(data,status,jqXHR){
console.log("2")
console.log(data)
console.log(status)
console.log(jqXHR)
init(data)
})
function init(data){
console.log("3")
console.log(data)
}
And here's the output:
> 1
> 2
> undefined
> undefined
> undefined
> 3
> (error because 'data' isn't defined)
So obviously, it's performing in the correct order, but I'm not getting the object back. Is this because it's not a jQuery object? If not...
What am I doing wrong here? I've looked at the docs, but it didn't have anything that pertains to this. I also checked a few posts:
jQuery When Done on dynamically pulled function call. However, this creates the promise object inside the function.
jQuery.when - Callback for when ALL Deferreds are no longer 'unresolved' (either resolved or rejected)?. This is performing the ajax call directly inside the
$.when
, similar to the docs.
But not finding an answer. Also, I realize there is something missing with my understanding of promises, so if someone could shed some light on what I did wrong, that would be a huge help.