javascript - 嵌套函数的返回值

标签 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;
        });
    }
}

最佳答案

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

关于javascript - 嵌套函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16864724/

相关文章:

javascript - 如何在 Angular2 中将从父级中的 dataService 接收到的数据传递给子级

javascript - 用 Node 调用本地类

javascript - JQUERY - 将选定的复选框移动到另一个页面

C++:未使用函数返回值时如何触发编译器错误?

c - 如果我们在 int main() 中返回字符串怎么办?

lua - 返回值数量

javascript - 具有不同高度响应高度的旋转木马

JavaScript - Daterangepicker,isInvalidDate 方法仅启用一天

c - 将指针返回到自身

c++ - 'List::operator=': 必须返回一个值