如何解决啦啦队处理另一个函数的错误后无法在 TRY 正文中获取数据
有这样一段代码:
const axios = require('axios');
const cheerio = require('cheerio');
let data = null;
const parseNewCorporations = async (iter) => {
let link2 = 'https://www.finanzen.net/aktien/' + iter.finanzen_net + '-aktie';
try{
await axios.get(link2)
.then(res => res.data)
.then(res => {
let html = res;
$ = cheerio.load( html,{ decodeEntities: false } );
let bigData = iter;
let price = $('div.snapshot-headline div.col-sm-7 div.row.quotebox:first-child div.col-xs-5.col-sm-4.text-sm-right.text-nowrap').text();
let currency = $('div.snapshot-headline div.col-sm-7 div.row.quotebox:first-child div.col-xs-5.col-sm-4.text-sm-right.text-nowrap span').text();
price = price.replace(currency,'').replace(',','.');
})
}
catch(e){
console.log(e.message,id =',iter.id,",finanzen_net = "+iter.finanzen_net);
await getAdditionPriceBilanzGuv(iter);
}
};
const getAdditionPriceBilanzGuv = async (iter) => {
//console.log('111',iter); // **here the code works correctly**
let link = 'https://www.finanzen.net/bilanz_guv/'+ iter.finanzen_net;
try{
await axios.get(link)
.then(res => res.data)
.then(res => {
console.log('getAdditionPriceBilanzGuv',iter);
// **here the code works NOT correctly**
})
}
catch(e){
if(e.message == 'Request path contains unescaped characters'){
console.log('Request path contains unescaped characters');
console.log({paramSubLink: iter.finanzen_net,corporations_id: iter.id});
}
else{
console.log('paramCorporationsId: ',iter.id);
//console.log('err- ',e);
}
}
};
function getApiData(){
// get request
return axios.get("https://seo-gmbh.eu/invest/daily.php",{
})
.then(response => {
return response.data;
})
.catch(function (error) {
console.log(error);
});
}
async function new_corporations() {
data = await getApiData();
let ii = 1;
for (let iter of data.new_corporations) {
//await parseNewCorporations(iter);
ii++;
await setTimeout(function(){
parseNewCorporations(iter);
},ii*3000);
}
//console.log(arrayCurrency);
}
new_corporations();
调用parseNewCorporations ()
函数后,会触发catch ()
异常,从而导致
可以在控制台中看到相应的消息。
问题是出现这个错误时,需要运行下面的函数getAdditionPriceBilanzGuv ()
,参数为iter
,在try {}
的body里面需要获取这个参数,不能完毕。
在此函数的最开始(在 try {}
的主体之外)(通过注释表示代码有效),可以获取此参数。
问题:
我缺少什么,如何在 try {}
的主体内的新调用函数中获取此参数?
如果无法做到这一点,有哪些替代实现可以解决这个问题?
附言在这种情况下,使用解析库 cheerio
解决方法
如果您使用 async/await,则不需要 then
s
let res = await axios.get(link2)
let $ = cheerio.load(res.data)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。