GETah
GETah

Reputation: 21409

How to return a JQuery promise

I have the following durendal code:

var variable = ko.observable("");
function activate(){
   return myModel.doSomething(variable);
}

doSomething is defined as follow:

function doSomething(variable){
    if(someCondition)
       return $.ajax(...).success(function(data){variable(data)});
    variable(defaultValue);
    return defaultValue;
}

This code works fine when someCondition==true, variable gets initialized with the ajax call results. when someCondition==false the activate method returns without the variable being initialized.

From what I read in the documentation, the happy path works because the ajax call returns a promise but not in the else case.

I tried this:

function activate(){
   return myModel.doSomething(variable).promise();
}

but I get an error saying that the observable does not have a promise method which makes sense.

Question How can I make the else clause return a promise just as what the ajax call does?

Upvotes: 0

Views: 780

Answers (1)

margabit
margabit

Reputation: 2954

You should better encapsulate the logic inside the doSomething function, so it always returns a promise. You can use the system.defer from Durandal to achieve this:

var system = require('durandal/system');

function doSomething(){
       return system.defer(function(dfd){
            if (someCondition)
                return $.ajax(...).then(function (res) {
                    dfd.resolve(res);
                });
            else
                dfd.resolve(defaultValue);
        }).promise();
}

And then in your activate:

function activate(){
   return myModel.doSomething().then(function(res){
         variable(res);
     });
}

Notice that the variable to be updated is no loger passed to the function. The promise will always return a value, either from the AJAX call or the default one.

Upvotes: 1

Related Questions