2017-05-15 115 views
0

有人能告訴我爲什麼,當「關於請求錯誤拒絕」遇到,這個功能也沒有什麼回我是從調用它的功能?node.js http GET - 爲什麼遇到錯誤時它不會返回調用函數?

我想返回到調用此功能的錯誤消息,但它出現在代碼只是停止遇到所表示的錯誤時執行。

function httpRequest(options, postData) { 
console.log('DEBUG - httpRequest - begin'); 
return new Promise(function(resolve, reject) { 
    console.log('DEBUG - httpRequest - a'); 
    var req = http.request(options, function(res) { 
     console.log('DEBUG - httpRequest - b'); 
     // reject on bad status 
     if (res.statusCode < 200 || res.statusCode >= 300) { 
      console.log('DEBUG - httpRequest - error: bad status ' + res.statusCode); 
      return reject(new Error('statusCode=' + res.statusCode)); 
     } 
     // cumulate data 
     var body = []; 
     res.on('data', function(chunk) { 
      body.push(chunk); 
     }); 
     // resolve on end 
     res.on('end', function() { 
      console.log('DEBUG - httpRequest - res.on end'); 
      try { 
       console.log('DEBUG - httpRequest - body = ' + body); 
       body = JSON.parse(Buffer.concat(body).toString()); 
      } catch(e) { 
       console.log('DEBUG - httpRequest - reject(e)'); 
       reject(e); 
      } 
      resolve(body); 
     }); 
    }); 
    // reject on request error 
    req.on('error', function(err) { 
     // This is not a "Second reject", just a different sort of failure 
     console.log('DEBUG - httpRequest - req.on error (second) err = ' + err.response); 
     reject(err); // *** <--- Why doesn't the error message here get returned to the calling function? 
    }); 
    if (postData) { 
     req.write(postData); 
    } 
    req.end(); 
    console.log('DEBUG - httpRequest - req.end'); 
}); 

}

+0

你妥善處理返回的承諾? – robertklep

+0

我喜歡這個調用它:HttpRequest的(選項,功能(錯誤,curConditions){ 的console.log( 'DEBUG - 164 - 錯誤=' + error.response); }); 根據我的console.log語句,它似乎沒有返回錯誤。 –

回答

1

httpRequest函數有兩個參數,optionspostData,並返回一個承諾。

your comment,你說明你這樣稱呼它:

httpRequest(options, function (error, curConditions) { ... }); 

這是不正確的原因有兩個:

  • 你逝去的是不是POST數據的第二個參數,但(回調)函數;
  • 你沒有正確處理退回的承諾;

調用它的正確方法:

httpRequest(options).then(function(curConditions) { 
    ... // handle the result 
}).catch(function(err) { 
    ... // handle the error 
}); 
+0

謝謝羅伯特!這解決了它。我已經編了很多年了,但是我現在是關於node.js的異步特性和使用promise的n00b。 –

+0

只要我能夠做到,我就會滿足你的回答(我的帳戶太新了)。 –

相關問題