【问题标题】:Async function returning empty value then doing operations?异步函数返回空值然后执行操作?
【发布时间】:2022-01-29 02:57:09
【问题描述】:

嘿,我已经在节点 js 中编写了这段代码

async function getUdemydata(){

    try{
        var finalData = []
        const res = await axios.get(baseUrl)
        const $ = cheerio.load(res.data);

        $('div[class="content"]').each(async (i,el) =>{
            const courseTitle = $(el).find("a").text()
            const aa = $(el).html() 
            const courseUrl = await getCoupenCode($(el).find("a").attr("href"))
            const courseDescription = $(el).find(".description").text().trim()
            const courseImage = await formateImageUrl($(el).find(".image").html())
            var dataObj = {
            "title": courseTitle,
            "description": courseDescription,
            "image": courseImage,
            "link": courseUrl
            }
            finalData.push(dataObj);
            console.log('appended');
        })
        return (finalData);
    } catch(error){
        console.error(error);
    }

}

(async()=>{
    var rs = await getUdemydata();
    console.log(rs);
})()

当我调用 getUdemydata() 函数时,仅在打印函数内部的 附加 之后打印空数组我应该在代码中更改什么以便函数返回最终结果数组

【问题讨论】:

    标签: node.js async-await


    【解决方案1】:

    .each的定义如下:

    each<T>(fn: (i: number, el: T) => boolean | void): Cheerio<T>
    

    它不支持Promise-aware,因此await 不支持您作为参数提供的异步函数。

    请记住,异步函数只是一个返回 Promise 的普通函数,因此您可以映射这些函数调用,最终得到一个 Promise 数组,然后等待它们。

    // var finalArray = [] // <-- NO
    const promises = $('div[class="content"]')
        .toArray()
        .map(async (el,i) => {
            // same body as `each` in your code
            // except, don't push into `finalArray`
            // just return your value
    
            // finalData.push(dataObj); // <-- NO
            return dataObj;
        });
    const finalArray = await Promise.all(promises);
    

    或者如果一次运行所有这些承诺的并行性太多,那么文档建议使用 Cheerio is Iterable,所以只需使用普通循环遍历 $('div[class="content"]')

    for(const el of $('div[class="content"]')) { //...
    

    【讨论】:

    • ...顺便说一句,请记住,数组上的所有其他高阶函数都倾向于使用 index 作为 2nd 参数来调用其选择器,该参数-.each(index, element) 的顺序以“让你失败”的方式逆势而上
    • @AnishGowda 我对代码进行了编辑,因为不需要将项目推送到finalArray
    猜你喜欢
    • 2012-06-03
    • 2015-12-26
    • 2013-12-23
    • 2022-01-11
    • 2022-06-27
    • 2021-07-16
    • 1970-01-01
    • 2018-04-14
    相关资源
    最近更新 更多