1

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:

  1. jQuery When Done on dynamically pulled function call. However, this creates the promise object inside the function.

  2. 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.

Travis Heeter
  • 13,002
  • 13
  • 87
  • 129
  • You should neither call `$.Deferred` nor `$.when` here. Try to just drop them. – Bergi May 01 '17 at 23:08
  • What do you expect with the `new DataModel(r)` to happen? You cannot `return` anything from the callback that you pass to`$.get`. – Bergi May 01 '17 at 23:09

1 Answers1

1

Some issues:

  • The callback function passed to $.get cannot be used to return a value that will resolve the Deferred object. Use then for this purpose.
  • $.get returns a Deferred object already, so there is no need to pass it to $.Deferred().
  • $.when is useful when you have more than one promise to resolve, but as you just have the one returned from your function, you don't need it, and can apply then directly on the function's return value.
  • There is nothing else passed to the then callback than only the promised value, so neither jqXHR nor status will be available.

Here is the corrected code:

function getDataModel(dataModelName = "dm1") {
    return $.get(url + dataModelName).then(function (r) {
        return new DataModel(r);
    });
}

and:

getDataModel(fromSelection).then(function (data) {
    console.log("2");
    console.log(data);
    init(data);
});
trincot
  • 317,000
  • 35
  • 244
  • 286