【问题标题】:How to get array outside of nested array node js如何在嵌套数组节点js之外获取数组
【发布时间】:2020-04-12 20:35:07
【问题描述】:

我是节点 js 的新手。我有一个控制器函数,我在其中创建自己的对象和数组。但我无法在最终循环之外获得最终数组。我还注意到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 []
    }
}

【问题讨论】:

  • 你能检查categories的值吗? console.log(categories) .. 可能是返回一个空数组。
  • @MEDZ 当我 console.log(categories) 它给了我一个包含我所有值的数组。
  • 数字“4”是在它之前还是之后记录的?
  • 与问题无关,但您正在循环访问 db,这不是一个好主意。我建议您一次性获取所有相关数据。
  • @SuleymanSah 你有任何例子吗?我对 nodejs 完全陌生

标签: javascript node.js mongoose promise


【解决方案1】:

您面临的问题是:在数组上调用 .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 []
}}

【讨论】:

  • 仍然控制台给我这个1 2 2 2 2 4 POST /api/league 200 82.341 ms - 293 3 3 3结果。
  • 你能澄清一下吗?这是从哪一行打印出来的,是否所有的 console.logs 都被触发了?
  • 所有控制台都在打印,但不是按顺序打印的。如您所见,1, 2 and 4 正在打印,但 3 最后打印。
  • 是的!它可以工作,但现在我认为内循环card.map(league => { 有问题。这仅在第一个数组中给出结果。
猜你喜欢
  • 2021-07-30
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
相关资源
最近更新 更多