0

関数を持つオブジェクトがあります。このように使用すると、常に が返されますundefinedthis.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 に答える