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

后端 未结 5 646
难免孤独
难免孤独 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条回答
  •  萌比男神i
    2020-11-29 21:39

    It's easier for you to use bluebird api, you can promisify request module and use the request function async as a promise itself, or you have the option of using the module request-promise, that makes you to not working to creating a promise but using and object that already encapsulates the module using promise, here's an example:

    var rp = require('request-promise');
    
    rp({host: '127.0.0.1',
        port: 4000,
        method: 'GET',
        path: '/api/v1/service'})
        .then(function (parsedBody) {
            // GET succeeded... 
        })
        .catch(function (err) {
            // GET failed... 
        });
    

提交回复
热议问题