Return value from promise / ajax call using jquery

var viewmodel = service.createCustomer(); is the way I call the requirejs module.

How do I create a deferred object that my createCustomer returns the CreateCustomerViewModel that is created inside the service call?

define(['viewmodels/CreateCustomerViewModel'],function (CreateCustomerViewModel) {

    function createCustomer() {
        $.getJSON('Customer/Create')
         .done(function (response) {
             return new CreateCustomerViewModel(response);
         })
         .fail(function (error) {
             alert(error);
         });
    }   

    return {        
        createCustomer: createCustomer        
    };
});
+4
source share
1 answer
  • You should use .then()instead .done()to change the payload.
  • You must allow your method createCustomerto return the modified payload.

The definition of your module will be as follows:

function createCustomer() {
    return $.getJSON('Customer/Create')
        .then(function (response) {
            return new CreateCustomerViewModel(response);
        });
}

return {
    createCustomer: createCustomer
};

Use as:

customerCreator.createCustomer()
    .done(function (model) {
        // yay! let use this model
    })
    .fail(function () {
        console.error("Cannot create customer");
    });

.fail() , , .

P.S. , POST GET ?

+6

All Articles