簡體   English   中英

從遞歸函數expressjs返回空數組?

[英]Returning empty array from the recursive function expressjs?

我試圖從 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;
}

test是一個異步函數,因此您將返回一個空的allCat數組。 您需要使用await test(categoryId)調用它,以便返回語句等待test解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM