2016-11-03 86 views
0

我正在使用restler(https://github.com/danwrong/restler)從外部來源進行api調用。在Sailsjs中,根據我的理解,幫助函數被稱爲服務。我把rest,rest等代碼放在自己的服務中,這樣我就不會重複使用相同的代碼。但是,在我的控制器中正常工作的restler函數不再適用於該服務。例如:Sailsjs外部模塊無法使用

//api/services/myService.js 
module.export{ 
     httpGet: function(){ 
     var rest = require('restler'); 
     rest.get('http://google.com').on('complete', function(result) { 
     if (result instanceof Error) { 
      console.log('Error:', result.message); 
      this.retry(5000); // try again after 5 sec 
     } else { 
      console.log(result); 
     } 
     }); 

    } 

} 

我知道我的服務正在正確使用;我試過從服務返回一個變量來檢查:

 httpGet: function(){ 
     var check = null; 
     var rest = require('restler'); 
     rest.get('http://google.com').on('complete', function(result) { 
     if (result instanceof Error) { 
      check = false; 
      console.log('Error:', result.message); 
      this.retry(5000); // try again after 5 sec 
     } else { 
      console.log(result); 
      check = true; 
     } 
     }); 
     return check; 
     //in the controller, myService.httpGet() returns null, not true or false 
    } 

任何幫助將不勝感激。 Salisjs v0.12.4

回答

2

最好讓服務接受回調。

//api/services/myService.js 
module.exports = { 
     httpGet: function(callback){ 
     var rest = require('restler'); 
     rest.get('http://google.com').on('complete', function(result) { 
     if (result instanceof Error) { 
      console.log('Error:', result.message); 
      return callback(result, null) 
      //this.retry(5000); // try again after 5 sec 
     } else { 
      console.log(result); 
      return callback(null, result) 
     } 
     }); 

    } 

} 

然後從你的控制器調用服務

myService.httpGet(function callback(err, result){ 
    // handle error 

    // use result 

}) 

時,另外對於你的問題,你是返回從服務return check;null你分配給它的價值早期傳遞一個回調。

PS:可以使用的承諾,而不是使用回調(callback hell

+1

一件小事。我認爲應該有'''module.exports = {'''。否則會出現語法錯誤。 – Bonanza

+0

@Bonanza是的。確實。這是一個錯字。 :) – MjZac

+0

謝謝。我從根本上誤解了回調;我試圖在函數中返回一個值。 – hamncheez

0

您應該httpGet功能導出爲模塊對象的屬性。基本上,你有一個「小」的錯字。取而代之的是:

module.export{ 
     httpGet: function(){ 

你應該有這樣的:

module.exports = { 
     httpGet: function(){ 

還有,如果你想返回的結果,添加callback

module.exports = { 
     httpGet: function(callback){ 
       ... 
       if (result instanceof Error) { 
        console.log('Error:', result.message); 
        return callback(result, null) 
       } else { 
        console.log(result); 
        return callback(null, result) 
       } 
        ... 

...或者使用承諾。