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

后端 未结 5 643
难免孤独
难免孤独 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:20

    There are other ways as well but here you can find a simple way to make http.request as a promise or async/await type.

    Here is a working sample code:

    var http = require('http');
    
    function requestAsync(name) {
    
        return new Promise((resolve, reject) => {
            var post_options = {
                host: 'restcountries.eu',
                port: '80',
                path: `/rest/v2/name/${name}`,
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            };
            let post_req = http.request(post_options, (res) => {
                res.setEncoding('utf8');
                res.on('data', (chunk) => {
                    resolve(chunk);
                });
                res.on("error", (err) => {
                    reject(err);
                });
            });
            post_req.write('test');
            post_req.end();
        });
    }
    
    //Calling request function
    //:1- as promise
    requestAsync("india").then(countryDetails => {
        console.log(countryDetails);
    }).catch((err) => {
        console.log(err);  
    }); 
    
    //:2- as await
    let countryDetails = await requestAsync("india");
    

提交回复
热议问题