有人可以告诉我为什么,当"拒绝请求错误"遇到这个函数时,这个函数不会向我调用它的函数返回任何内容吗?
我想要一个错误消息返回给调用它的函数,但是当遇到指示的错误时,代码就会停止执行。
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 :(得分:1)
httpRequest
函数有两个参数options
和postData
,它会返回一个承诺。
在your comment中,你说的是你这样称呼它:
httpRequest(options, function (error, curConditions) { ... });
这有两个原因:
调用它的正确方法:
httpRequest(options).then(function(curConditions) {
... // handle the result
}).catch(function(err) {
... // handle the error
});