2015-06-28 33 views
5

Sözler ile kod yazmayı anlamaya çalışıyorum. Kodumu kontrol et plz. Bu doğru?node.js + request => node.js + bluebird + istek

node.js + isteği:

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 + bluebird + isteği:

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

Nasıl tepki durumunu kontrol etmek? İlk örnekten mi yoksa daha ilginç bir şey mi kullanmalıyım? durum kodu kontrol etmek

+2

'jsonString' nereden geldi? – thefourtheye

+0

@thefourtheye sry, catch (e) kısmını unutun {...} –

cevap

11

Sadece response.statusCode olmadığını kontrol edebilirsiniz spread işleyicisi değil 200 ve catch işleyicisi icabına böylece, o bir Error atmak . Bu

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); 

gibi bunu uygulayabilirsiniz Ve dikkat ederseniz JSON.parse bir zaman uyumsuz fonksiyon olmadığı için, biz, spread işleyicisinden çözümlenen JSON dönmek, bu yüzden ayrı bir then işleyicisi bunu yapmak gerekmez .

0

Tek yönlü:

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