0

I have a class with a method which gets something from the server. I'm trying to find a way to be able to return "something" from the function that later "becomes" the data which the server responds with. Here's the idea:

@find: (id) ->
  response = THING
  $.ajax
    type: 'GET'
    url: "#{this::url}/#{id}"
    dataType: 'json'
    success: (data) =>
      response.become @init(data)
    error: (xhr, status, error) ->
      response.reject error
  response

The use of this method would look like this:

myBlah = Product.find(1)

I recognize that this is similar to the concept of a promise, which I'm only vaguely familiar with. Is there something I'm missing here?

1 Answers1

1

Try setting the 'async' option of $.ajax to false. If at all possible try working with callbacks. I've added a solution for both scenarios.

var Product = {};
Product.find = function(id) {

    var response;
    $.ajax({
        async: false,
        type: 'GET',
        url: "/product/" + id,
        dataType: 'json',
        success: function(data) {
            response = new ProductModel(data);
        },
        error: function(xhr, status, error) {
            response = null;
        }
    });
    return response;

};

var myProduct = Product.find(1);
if (myProduct != null) {
    myProduct.getPrice();
}

Here's how the above code would work using a callback function.

var Product = {};
Product.find = function(id, callback) {

    $.ajax({
        type: 'GET',
        url: "/product/" + id,
        dataType: 'json',
        success: function(data) {
            var response = new ProductModel(data);
            if (typeof callback != 'undefined') {
                callback(response);
            }
        },
        error: function(xhr, status, error) {
            if (typeof callback != 'undefined') {
                callback(null);
            }
        }
    });

};

Product.find(1, function(myProduct) {
    if (myProduct != null) {
        myProduct.getPrice();
    }
});