我正在使用 request-promise
模块来检查站点是否正在使用代理。我试图找到速度足以在 5 秒内回答的代理。因此,我仅在请求未在 5 秒内超时时才添加对象。
对于某些代理,即使 promise 已解析, Node 脚本也会挂起一段时间。我找不到延迟的原因。我看到它打印了 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);
});
最佳答案
对于您的用例,我建议您使用 Promise.race()
它的行为与 Promise.all
相同,但您会在最快的代理响应后立即获得回调。
我对该错误进行了更多调查,它似乎是 a request
module issue ,当你使用超时时,他们只是不关闭连接,它处于挂断状态
关于javascript - 即使已解决,Promise 也会挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45876349/