承诺即使已经解决也会挂起

时间:2017-08-25 07:27:50

标签: javascript node.js requestjs

我正在使用request-promise模块检查网站是否正在使用代理。我试图找到足够快的代理,在5秒内回答。因此,如果请求在5秒内没有超时,我只会添加对象。

对于某些代理,即使promise解析,节点脚本也会挂起一段时间。我无法找到这种延迟的原因。我看到它打印Done但它挂起了。 1分钟后10秒钟,脚本退出。由于我的代码或打开的套接字等的操作系统问题,这是否挂起?

const rp =  require('request-promise');
const testProxies = [
    {
       "ipAddress": "80.241.219.83",
       "port": 3128,
    },
    {
        "ipAddress": "45.55.27.246",
        "port": 80
    },
    {
        "ipAddress": "144.217.197.71",
        "port": 8080,
    },
    {
        "ipAddress": "104.131.168.255",
        "port": 80,
    },
    ];

function CheckSites(sitesArray,site) {
    let ps = [];
    for (let i = 0; i < sitesArray.length; i++) {
        let proxy = sitesArray[i];

        let ops = {
            method: 'GET',
            resolveWithFullResponse: true,
            proxy: 'http://' + proxy.ipAddress + ':' + proxy.port,
            uri:site,
        };
        let resp =  rp.get(ops);
        ps.push(resp);
    }
    return Promise.all(ps.map(function (p) {
        p.time =  Date.now();
        return p
            .then(function (a) {
                return {'header':a.headers,'time':Date.now() - p.time};
            })
            .timeout(5000)
            .catch(function (e) {
                return {};
            })
    }))
}
CheckSites(testProxies,'https://www.example.com').then(function (object) {
    console.log('Done!');
    console.log(object);
}).catch(function (err) {
    console.log('Exception: ' + err);
});

1 个答案:

答案 0 :(得分:1)

对于您的使用案例,我建议您使用Promise.race(),其行为为Promise.all,但只要最快的代理响应,您就会收到回调。

我已经对错误进行了更多调查,似乎是a request module issue,当您使用超时时,他们只是不会关闭连接并且它处于挂机状态州