主函数如下, 其中 mongoose 用了 bluebird 模块实现 Promise:
/** 根据查询条件生成栏目树 * {pid: 0} 全栏目树 * {_id: ObjectId('xxxx')} 指定顶级栏目栏目树 * 若 loop=false, 则只返回一层, 不递归遍历 **/ async function getTree(query, loop=true) { const tree = await Category.find(query); if ( loop === false ) return tree; tree.map( async (item) => { let children = await Category.find({ status: true, pid: mongoose.Types.ObjectId(item._id) }); item.children = children; // Object.assign(item, {children}); console.dir(item); } ); return tree; } );
结果发现返回的 tree 对象数组中的对象没有 children 属性?试了 Object.assign 一样无效, 但在 map 方法里 console.dir(item)又能看到 children 属性?
或者你们遇到这种无限级分类是怎么输出栏目树的?
![]() | 1 abcdGJJ 2018-10-30 09:19:06 +08:00 via Android 把 map 换成 for 循环试试,好像 map 里的异步函数会有问题 |
2 ilaipi 2018-10-30 09:25:39 +08:00 #1 说的是对的,要改成 for,map 这种是回调函数,async 没用。另外你可以去了解一下 populate,看你的需求大概能一次查询出来。 |
![]() | 3 licoycn 2018-10-30 09:28:44 +08:00 兄弟 撞头了 |
![]() | 4 gyteng 2018-10-30 09:32:01 +08:00 map 不能这么用,非得这样用的话,先 map 出一个 promise 数组,再 Promise.all 调用出结果 |
![]() | 5 xuyl OP |
![]() | 7 owenliang 2018-10-30 09:35:38 +08:00 async await 真牛逼。。 |
8 meko 2018-10-30 09:38:24 +08:00 ```bash async function getTree(query, loop=true) { const tree = await Category.find(query); if ( loop === false ) return tree; tree = tree.map( async (item) => { //转成 object item = item.toObject(); let children = await Category.find({ status: true, pid: mongoose.Types.ObjectId(item._id) }); item.children = children; console.dir(item); return item; } ); return tree; } ); ``` |
![]() | 10 fanshide 2018-10-30 09:42:00 +08:00 map 内部是不支持异步的,推荐了解下 for await of ;或者先得到一个 promise 数组,再使用 Promise.all() |