使用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;
                });

我遇到的问题是:尝试调试时看到:

  1. const allTdTest = depRequest.then( async $ => {被“执行”而不执行函数主体
  2. allTdTest.then( () => {....}被执行并返回数组的大小为0
  3. 执行depRequest.then( async $ => { 的正文。

我没有使用forEach,而是来自cheerio模块的.each()函数。 据我了解,cheerio .each()是同步的,但我想在内部执行的操作却不是。

关于我所缺少的任何建议吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)