2013-05-31 4 views
0

함수가있는 객체가 있습니다. 이 방법을 사용하면 항상 undefined을 반환합니다. this.client[method].read(params).done 함수가 반환하는 값을 반환하려면 어떻게해야합니까?중첩 함수의 반환 값

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

입니까? 당신이 활용할 수있는 일종의 약속 시스템을 사용하는 것처럼 보입니다. –

+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

이 약속 시스템을 사용하는 것 때문에를, 그것은 것 같다 여기

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

는 객체의 .read(params)의 결과를 반환 한 다음 cal 대신 callback을 사용하여 .done()으로 전화하면됩니다. .get() 안에 있습니다. 이것은 무엇 API

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