2015-06-28 79 views
5

我试图了解如何使用promise来编写代码。 查看我的代码plz。这是对的?node.js + request => node.js + bluebird +请求

的Node.js +要求:

request(url, function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
     var jsonpData = body; 
     var json; 
     try { 
      json = JSON.parse(jsonpData); 
     } catch (e) { 
      var startPos = jsonpData.indexOf('({'); 
      var endPos = jsonpData.indexOf('})'); 
      var jsonString = jsonpData.substring(startPos+1, endPos+1); 
      json = JSON.parse(jsonString); 
     } 
     callback(null, json); 
    } else { 
     callback(error); 
    } 
}); 

的Node.js +蓝鸟+要求:

request.getAsync(url) 
    .spread(function(response, body) {return body;}) 
    .then(JSON.parse) 
    .then(function(json){console.log(json)}) 
    .catch(function(e){console.error(e)}); 

如何检查响应状态?我应该使用从第一个例子或更有趣的东西?检查状态代码

+2

'jsonString'从哪里来的? – thefourtheye

+0

@thefourtheye sry,忘记部分catch(e){...} –

回答

11

你可以简单地检查response.statusCode不是200在spread处理程序,并抛出从一个Error,使catch处理器将照顾它。您可以实现像这样

var request = require('bluebird').promisifyAll(require('request'), {multiArgs: true}); 

request.getAsync(url).spread(function (response, body) { 
    if (response.statusCode != 200) 
     throw new Error('Unsuccessful attempt. Code: ' + response.statusCode); 
    return JSON.parse(body); 
}).then(console.log).catch(console.error); 

如果你注意到了,我们从spread处理程序返回解析JSON,因为JSON.parse不是一个异步函数,所以我们没有做,在一个单独的then处理器。

0

方式一:

.spread(function(response, body) { 
    if (response.statusCode !== 200) { 
    throw new Error('Unexpected status code'); 
    } 
    return body; 
})