node.js http GET - 为什么在遇到错误时它没有返回到调用函数?

时间:2017-05-15 07:47:56

标签: node.js promise

有人可以告诉我为什么,当"拒绝请求错误"遇到这个函数时,这个函数不会向我调用它的函数返回任何内容吗?

我想要一个错误消息返回给调用它的函数,但是当遇到指示的错误时,代码就会停止执行。

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

}

1 个答案:

答案 0 :(得分: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
});