如何解决使用cheerio .each的NodeJS异步功能无法正常工作
我目前正在尝试学习节点JS。 我正在尝试抓取一些数据,然后将其插入mysql DB中。一切工作正常,但我不明白为什么,在函数完成其工作之前调用function.then()会执行。 这是代码:
const depRequest = getHtmlFromUrl(url)
let deps_id = [];
const allTdTest = depRequest.then( async $ => {
try{
// Process departments data
return $(tableSelectorDip).each(async (i,el) => {
try {
// Scrape data from departments
const obj = await extractDipStats($(el),$);
// console.log("Name: " + obj.name + "\nId: " + obj.unict_id);
// Insert data into DB
const result = await insert_dip(obj.unict_id,year,obj.name);
// console.log(result)
// Push id to scrape cds
deps_id.push(obj.unict_id);
// console.log("Deps: " + deps_id);
} catch (error) {
console.error(error);
}
});
} catch(error) {
console.error(error);
}
});
allTdTest.then( () => {
console.log("Finito td");
console.log("Deps id: " + deps_id.length)
})
其中getHtmlFromUrl是一个类似于以下功能的函数:
/**
* Using axios to get html code,if succeeds uses cheerio to load html
* In order to work with CSS Selectors and jQuery.
* @param {String} url
*/
const getHtmlFromUrl = async url => {
return await axios.get(url)
.then(response => cheerio.load(response.data))
.catch(error => {
error.status = (error.response && error.response.status) || 500;
throw error;
});
我遇到的问题是:尝试调试时看到:
-
const allTdTest = depRequest.then( async $ => {
被“执行”而不执行函数主体 -
allTdTest.then( () => {....}
被执行并返回数组的大小为0 - 执行
depRequest.then( async $ => {
的正文。
我没有使用forEach,而是来自cheerio模块的.each()函数。 据我了解,cheerio .each()是同步的,但我想在内部执行的操作却不是。
关于我所缺少的任何建议吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。