如何在嵌套数组节点js之外获取数组

时间:2019-12-20 10:07:08

标签: javascript node.js mongoose promise

我是Node js的新手。我有一个控制器函数,可以在其中创建自己的对象和数组。但是我无法在final循环之外获取final数组。我还注意到console.log("3")无法正常工作,并直接调用console.log("4");

这是代码

async function fetchLeague(req, res, next) {
    try {
        //get types
        let types = await Leaguetype.find({});

        let mainarray = {};
        mainarray['filters'] = [];
        console.log("1");
        types.map(async (type) => {
            console.log("2");
            let typess = {};
            typess.title = type.title;
            typess.totalCards = '5';
            typess.sections = [];
            mainarray['filters'].push(typess);
            var categories = await Leaguecategories.find({"league_type_id": type._id}) ;
            categories.map(async (category) => {
                console.log("3");
                let allcategories = {};
                allcategories.id = category._id;
                allcategories.title = category.name;
                allcategories.cards = [];
                typess.sections.push(allcategories);
                let card = await League.find({"league_category_id": category._id}) ;
                card.map(async (league) => {
                    let allleague = {};
                    allleague.card_title = league.title; 
                    allleague.pool_price = league.pool_price; 
                    allleague.entry_fee = league.entry_fee; 
                    allleague.total_spots = league.total_spots; 
                    allleague.start_time = league.start_time; 
                    allleague.end_time = league.end_time; 
                    allcategories.cards.push(allleague);


                });
            });
        });
        console.log("4");
        res.send({status: 0, statusCode:"success", message: "Successfully 1 inserted.", data:  mainarray});
    } catch (error) {
        console.log('no', error);
        return []
    }
}

1 个答案:

答案 0 :(得分:0)

您面临的问题是:在数组上调用.map并提供异步函数会返回一个promise数组,而不是一个转换值数组。

const arr = ["test1","test2","test3"]
const returned = arr.map(async (val) => val)
returned.forEach(val => console.log(val.__proto__.toString()))

这也是为什么未调用console.log(“ 3”)的原因,因为您没有等待诺言。这意味着,节点只是跳过它,然后继续执行您的代码。

这应该可以解决您的问题

async function fetchLeague(req, res, next) {
try {
    //get types
    let types = await Leaguetype.find({});

    let mainarray = {};
    mainarray['filters'] = [];
    console.log("1");
    Promise.all(types.map(async (type) => {
        console.log("2");
        let typess = {};
        typess.title = type.title;
        typess.totalCards = '5';
        typess.sections = [];
        mainarray['filters'].push(typess);
        var categories = await Leaguecategories.find({"league_type_id": type._id}) ;
        await categories.map(async (category) => {
            console.log("3");
            let allcategories = {};
            allcategories.id = category._id;
            allcategories.title = category.name;
            allcategories.cards = [];
            typess.sections.push(allcategories);
            let card = await League.find({"league_category_id": category._id}) ;
            card.map(league => {
                let allleague = {};
                allleague.card_title = league.title; 
                allleague.pool_price = league.pool_price; 
                allleague.entry_fee = league.entry_fee; 
                allleague.total_spots = league.total_spots; 
                allleague.start_time = league.start_time; 
                allleague.end_time = league.end_time; 
                allcategories.cards.push(allleague);


            });
        });
    })).then(() => {
         console.log("4");
         res.send({status: 0, statusCode:"success", message: "Successfully 1 inserted.", data:  mainarray});
    });
} catch (error) {
    console.log('no', error);
    return []
}}