【发布时间】:2020-04-07 13:50:36
【问题描述】:
我正在尝试使用 axios 和 cheerio 获取网页,但我无法检索所有数据,因为即使在内部过程完全之前,函数正在返回完毕。我正在使用 ReactJS,当我单击页面中的按钮时,会调用此函数:
analyse = async(e) => {
this.a = await axios.get('xxx');
this.s = await axios.get('yyy');
this.f = await axios.get('zzz');
let aReturn = this.fetchA(this.a.data);
let sReturn = this.fetchS(this.s.data);
let fReturn = this.fetchF(this.f.data);
if(await fReturn === true && await aReturn === true && await sReturn === true){
anotherFunction();
}
}
在上面的代码中,axios 工作正常,函数fetchA() 和fetchS() 是简单的函数,没有任何进一步的内部函数调用:
fetchA(html){
const $ = cheerio.load(html);
//some process
return true;
}
fetchS(html){
const $ = cheerio.load(html);
//some process
return true;
}
没有完全执行就返回的函数是fetchF():
fetchF(html){
const $ = cheerio.load(html);
$('div._someClassName').children().each((i,elem) => {
let link = $(elem).find('a').first().attr('href');
axios.get(link)
.then(response => {
this.deepF(response.data);
})
.catch(err => {
console.log("Error : ",err);
})
};
return true;
}
在上面的函数中,每个孩子都有一个唯一的链接,我需要再次axios.get() 并调用另一个函数deepF() 来获取该页面的数据。
内部函数 deepF 又是一个小函数:
deepF(html){
const $ = cheerio.load(html);
//some process
return true;
}
在整个代码中,fetchF() 在内部没有完全执行所有 deepF() 函数的情况下返回 true。
注意:fetchF() 返回 true 后,所有deepF() 函数稍后执行缓慢
如何等待fetchF() 执行所有内部deepF(),然后在fetchF() 中返回true?
【问题讨论】:
标签: reactjs promise callback cheerio asynchronous-javascript