首页 新闻 会员 周边

nodejs操作mongodb 异步查询怎么同步,代码如下:获取不到 GetName(item)这个的值

0
[待解决问题]

/////GetName()

function GetName(Id) {
let name = '';

user.findById(Id, (err, res) => {
if(err) {
return;
}
name = res.name;
})
return name;
}

///调用函数GetName

var GetIdName = function GetIdName(Ids) {

let user_detail= [];

Ids.forEach(function(item, i, Ids) {
let user= {};
let this_id = item;
user.b_id = this_id;
user.b_name = GetName(item);

user_detail.push(user); 

});

return user_detail;

}

 

GetIdName(Ids);

console.log(GetIdName(Ids))

问题补充:

 换了个方法,使用settimeout(function(){},3000)

(没试过数据量大的情况下是什么样的,待研究)

let Ids = eval(request.payload.Branch_Id);
                    let branch_detail = [];
                    Ids.forEach(function(item, index, Ids) {                    
                        let name = '';
                        Branch.findById(item, (err, res) => {
                            name = res.Code_Batch;
                            let branch = {
                                branch_id: item,
                                branch_name: name
                            };
                            branch_detail.push(branch);
                        });
                    })
                    
                    let doc = {};
                    doc.branch_detail = branch_detail;
                    doc.belong = accountobj._id;
                    setTimeout(function() {
                        Activity.create(doc, (err, res) => {
                            console.log(branch_detail);//此处输出的是有值的
                             if(err) {
                                return reply({
                                    code: 530,
                                    msg: '连接数据库失败',
                                    data: null
                                });
                            }
                            return reply({
                                code: 0,
                                msg: '添加成功',
                                data: res
                            });
                        })
                    }, 3000);

 

沫沫w的主页 沫沫w | 菜鸟二级 | 园豆:202
提问于:2018-07-17 14:44
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册