2015-10-14 88 views
0

我試圖圍繞承諾包圍我的頭,但到目前爲止我似乎無法得到簡單的示例工作。這裏它是一個代碼來請求服務器的JSON:請求-json與藍鳥承諾的奇怪行爲

module.exports = function (app, options) { 
var promise = require('bluebird'); 
var request = require('request-json'); 

var module = { 
    url: options.url, 
    httpClient: promise.promisifyAll(request.createClient(options.url)) 
}; 

module.getSample = function() { 
    return this.httpClient.getAsync('sample/') 
     .then(function(error, response, body) { 
      console.log(body); 
     }) 
     .catch(function(e) { 
      console.log('error'); 
      console.log(e); 
     }); 
}; 

return module; 

};

但是當我這樣稱呼它:

var backendClient = require('./utils/backendClient.js')(app, { 
    url: 'http://localhost:8080/' 
}); 

backendClient.getSample() 

在運行時我得到一個錯誤說「[語法錯誤:意外的令牌O]」。沒有承諾的版本工作正常。我錯過了什麼?

+0

你從哪裏得到語法錯誤,在哪個文件的哪一行? – Bergi

+0

編輯了問題 – chester89

+0

我習慣於從JSON.parse中看到'Unexpected token o' - 你確定你得到了一個JSON嗎?另外一個promise只能用一個值來解析,所以你的'error,response,body'簽名是不正確的,看最新的最簡單的方法就是'console.log(arguments)',看看解析的對象是什麼 – Madd0g

回答

1
module.getSample = function() { 
    return this.httpClient.getAsync('sample/') 
     .then(function(error, response, body) { 
      // not sure what Promise library you are using, but in the Promise/A+ spec, the function in then only receives a single argument, the resolved value of the Promise 
      console.log(body); 
      // this returns equivalent to Promise.resolve(undefined); 
      // you really want to return something meaningful here 
     }) 
     .catch(function(e) { 
      console.log('error'); 
      console.log(e); 
      // this also returns equivalent to Promise.resolve(undefined); 
      // to propagate the "error" condition, you want to either throw e, or return Promise.reject(something here); 
     }); 
}; 

這將始終與未定義返回fullfilled承諾的價值,從來沒有被拒絕的一個。其他錯誤評論以上

+0

謝謝,這一切都奏效了 - 我用傳播而不是然後添加return語句 – chester89