0

I have an object with a function. When I use it this way, it always returns undefined. How can I make it return whatever this.client[method].read(params).done function returns?

rest.get('search', {query: 'Eminem', section: 'tracks'})

Here's the object:

var rest = {

    // configuration
    base: 'http://localhost/2.0/',
    client: null,

    get: function (method, params) {

        // if client is null, create new rest client and attach to global
        if (!this.client) {
            this.client = new $.RestClient(this.base, {
              cache: 5 //This will cache requests for 5 seconds
            });
        }

        // add new rest method
        if (!this.client[method]) {
            this.client.add(method);
        }

        // make request
        this.client[method].read(params).done(function(response) {
            //'client.foo.read' cached result has expired
            //data is once again retrieved from the server
            return response;
        });
    }
}
Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
Jurager
  • 45
  • 6

2 Answers2

3
get: function (method, params, callback) {

    // if client is null, create new rest client and attach to global
    if (!this.client) {
        this.client = new $.RestClient(this.base, {
          cache: 5 //This will cache requests for 5 seconds
        });
    }

    // add new rest method
    if (!this.client[method]) {
        this.client.add(method);
    }

    // make request
    this.client[method].read(params).done(function(response) {
        //'client.foo.read' cached result has expired
        //data is once again retrieved from the server
        callback(response);
    });
    /*
    simpler solution:
    this.client[method].read(params).done(callback);
    */
}

It's asynchronous code, so you must use callbacks:

rest.get('search', {query: 'Eminem', section: 'tracks'}, function(response) {
    // here you handle method's result
})
wachme
  • 2,327
  • 20
  • 18
2

Since this seems to use a Promise system, it would seem that you could just return the result of .read(params), and then call .done() with the callback instead of calling it inside the .get().

var rest = {
    // configuration
    base: 'http://localhost/2.0/',
    client: null,

    get: function (method, params) {

        // if client is null, create new rest client and attach to global
        if (!this.client) {
            this.client = new $.RestClient(this.base, {
              cache: 5 //This will cache requests for 5 seconds
            });
        }
        // add new rest method
        if (!this.client[method]) {
            this.client.add(method);
        }

    // Just return the object
        return this.client[method].read(params));
    }
}

rest.get('search', {query: 'Eminem', section: 'tracks'})
    .done(function(response) {
        // use the response
    });