0

我有一个具有功能的对象。当我以这种方式使用它时,它总是返回undefined. 我怎样才能让它返回任何this.client[method].read(params).done函数返回?

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

这是对象:

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;
        });
    }
}
4

2 回答 2

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);
    */
}

它是异步代码,所以你必须使用回调:

rest.get('search', {query: 'Eminem', section: 'tracks'}, function(response) {
    // here you handle method's result
})
于 2013-05-31T19:45:43.557 回答
2

由于这似乎使用了 Promise 系统,因此您似乎可以只返回 的结果.read(params),然后.done()使用回调调用而不是在.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
    });
于 2013-05-31T19:52:24.570 回答