我正在尝试使用request-promise
模块来检查多个网站。如果我按照设计使用Promise.all
,则promise会以第一次拒绝返回。执行多个请求任务并等待所有请求完成它们是否已完成或被拒绝的正确方法是什么?我想出了以下两个功能。
CheckSitesV1
会返回异常。然而,CheckSitesV2
等待所有承诺完成他们是否满足或被拒绝。如果你能评论我写的代码是否有意义,我将不胜感激。我使用的是NodeJS v7.9.0
const sitesArray = ['http://www.example.com','https://doesnt-really-exist.org','http://www.httpbin.org'];
async function CheckSitesV1() {
let ps = [];
for (let i = 0; i < sitesArray.length; i++) {
let ops = {
method: 'GET',
uri:sitesArray[i],
};
const resp = await rp.get(ops);
ps.push(resp);
}
return Promise.all(ps)
}
function CheckSitesV2() {
let ps = [];
for (let i = 0; i < sitesArray.length; i++) {
let ops = {
method: 'GET',
uri:sitesArray[i],
};
ps.push(rp.get(ops));
}
return Promise.all(ps.map(p => p.catch(e => e)))
}
CheckSitesV1().then(function (result) {
console.log(result);
}).catch(function (e) {
console.log('Exception: ' + e);
});
CheckSitesV2().then(function (result) {
console.log(result);
}).catch(function (e) {
console.log('Exception: ' + e);
});
答案 0 :(得分:2)
你的
driver.ExecuteScript("$x(""//label[text()[contains(.,'British')]]"")[0].children[1].children[0].click()")
完全没问题。我只能建议重构一点以便于阅读:
function CheckSitesV2() {
let ps = [];
for (let i = 0; i < sitesArray.length; i++) {
let ops = {
method: 'GET',
uri:sitesArray[i],
};
ps.push(rp.get(ops));
}
return Promise.all(ps.map(p => p.catch(e => e)))
}
关于异步试试这个
function CheckSitesV2() {
let ps = sitesArray
.map(site => rp.get({method: 'GET', uri: site}).catch(e => e));
return Promise.all(ps);
}