2015-10-14 89 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