我需要以下格式的猫鼬find().exec
的结果。可以像这样格式化结果吗?
var myFunction = function(foo, bar) {
model1.find({ elem: foo, elem2: bar }).exec(function(err, data) {
if (err) {
/* ... */
}
if (data) {
if (data.passed == true) {
return { passed: true, point: data.point };
} else {
return { passed: false, point: data.point };
}
} else {
return { passed: false, point: "not tried" };
}
});
};
object = {
...
someitem: array.map(function(arr) {
return {
_id: program._id,
title: program.title,
slug: program.slug,
status: myFunction(arr._id, arr._id2) /* Like This */
};
});
...
}
请原谅我的英语不好:D
答案 0 :(得分:0)
您必须从函数返回promise才能获取猫鼬查询中即将出现的值。因此请将函数更改为:
var myFunction = function(foo,bar) {
return new Promise(function(resolve, reject){
model1.find({elem : foo, elem2 : bar}).exec(function (err, data){
if(err){
/* Blablabla*/
reject(err);
}
if(data){
if(data.passed == true){
resolve({passed:true, point:data.point});
} else {
resolve({passed:false, point:data.point});
}
} else {
resolve({passed:false, point:'not tried});
}
});
});
}
比起您要调用该函数并获取值,您必须这样做:
let promises, obj_elem = [];
for(let i =0;i < array.length;i++){
promises.push(myFunction(array[i]._id, array[i]. _id2));
}
/* You can't do it sync manner so you have to use some kind of async process */
Promise.all(promises).then((result)=>{
for(let i =0;i < result.length;i++){
obj_elem.push({
_id: program._id,
title: program.title,
slug: program.slug,
status: result[i].passed
});
}
console.log(obj_elem); //here you will have values you want
});