2015-06-28 77 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; 
})