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

Mea*_*her 5 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);
});
Run Code Online (Sandbox Code Playgroud)

Ale*_*aru 1

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

我已经对这个错误进行了更多调查,这似乎是一个request模块问题,当您使用超时时,他们只是不关闭连接并且处于挂起状态