2013-05-31 120 views
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; 
     }); 
    } 
} 
+0

什麼API這是什麼?似乎它使用某種Promise系統,你可以利用。 –

+0

此代碼使用jquery-rest與apis一起工作[link](https://github.com/jpillora/jquery.rest) – Jurager

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

由於這似乎用一個承諾制,這似乎您可以返回.read(params)的結果,然後用回叫代替cal調用.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 
    });