【问题标题】:Returning empty array from the recursive function expressjs?从递归函数expressjs返回空数组?
【发布时间】:2020-04-08 18:58:42
【问题描述】:

我正在尝试从 MongoDB 获取所有子元素, 我编写了一个递归函数来获取所有子元素。 它遍历所有值,我可以控制台记录所有值 在循环内部,当我将值推送到数组并返回值时,我得到一个空数组。 我正在 expressjs 中编写此代码 代码如下

static async getAllChildCat(categoryId){

    var allCat = [];

    let test = async (categoryId) => {
        let category = await NewCategory.find({ 'parent': categoryId });
        if (category.length > 0) {
            await category.forEach(async elem => {
                let newVal = await test(elem._id);
                console.log(elem);
                allCat.push(elem);
            });
        }
    }

    var val = await test(categoryId);

    return allCat;
}

【问题讨论】:

    标签: javascript mongodb express mongoose async-await


    【解决方案1】:

    test 是一个异步函数,因此您将返回一个空的 allCat 数组。您需要使用 await test(categoryId) 调用它,因此 return 语句等待 test 解析。

    【讨论】:

    • 如果你添加 await 它也会给出空数组。我试过了,请检查上面的代码,我已经更新了
    猜你喜欢
    • 2021-08-14
    • 2019-04-25
    • 2020-10-10
    • 2013-08-07
    • 1970-01-01
    • 2015-10-23
    • 2015-04-27
    • 1970-01-01
    相关资源
    最近更新 更多