nodejs - How to promisify http.request? reject got called two times

后端 未结 5 647
难免孤独
难免孤独 2020-11-29 20:37

I\'m trying to wrap http.request into Promise:

 new Promise(function(resolve, reject) {
    var req = http.request({
        host:          


        
5条回答
  •  借酒劲吻你
    2020-11-29 21:36

    I know this question is old but the answer actually inspired me to write a modern version of a lightweight promisified HTTP client. Here is a new version that:

    • Use up to date JavaScript syntax
    • Validate input
    • Support multiple methods
    • Is easy to extend for HTTPS support
    • Will let the client decide on how to deal with response codes
    • Will also let the client decided on how to deal with non-JSON bodies

    Code below:

    function httpRequest(method, url, body = null) {
        if (!['get', 'post', 'head'].includes(method)) {
            throw new Error(`Invalid method: ${method}`);
        }
    
        let urlObject;
    
        try {
            urlObject = new URL(url);
        } catch (error) {
            throw new Error(`Invalid url ${url}`);
        }
    
        if (body && method !== 'post') {
            throw new Error(`Invalid use of the body parameter while using the ${method.toUpperCase()} method.`);
        }
    
        let options = {
            method: method.toUpperCase(),
            hostname: urlObject.hostname,
            port: urlObject.port,
            path: urlObject.pathname
        };
    
        if (body) {
            options.headers = {'Content-Length':Buffer.byteLength(body)};
        }
    
        return new Promise((resolve, reject) => {
    
            const clientRequest = http.request(options, incomingMessage => {
    
                // Response object.
                let response = {
                    statusCode: incomingMessage.statusCode,
                    headers: incomingMessage.headers,
                    body: []
                };
    
                // Collect response body data.
                incomingMessage.on('data', chunk => {
                    response.body.push(chunk);
                });
    
                // Resolve on end.
                incomingMessage.on('end', () => {
                    if (response.body.length) {
    
                        response.body = response.body.join();
    
                        try {
                            response.body = JSON.parse(response.body);
                        } catch (error) {
                            // Silently fail if response is not JSON.
                        }
                    }
    
                    resolve(response);
                });
            });
    
            // Reject on request error.
            clientRequest.on('error', error => {
                reject(error);
            });
    
            // Write request body if present.
            if (body) {
                clientRequest.write(body);
            }
    
            // Close HTTP connection.
            clientRequest.end();
        });
    }
    

提交回复
热议问题