从嵌套函数返回值

时间:2013-05-31 19:42:57

标签: javascript return-value

我有一个带有函数的对象。当我以这种方式使用它时,它总是返回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;
        });
    }
}

2 个答案:

答案 0 :(得分: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
})

答案 1 :(得分:2)

由于这似乎使用了Promise系统,您似乎只能返回.read(params)的结果,然后使用回调调用.done()而不是在{{1}内调用它}。

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