如何从查询结果中创建对象?在用餐时,该表与对数据库的查询一起使用。如果查询是异步的,该怎么办?
const returnResultOfQuery = () => {
Dinner1300.count().exec(function (err, count) {
const random = Math.floor(Math.random() * count)
Dinner1300.findOne().skip(random).exec(
function (err, result) {
console.log(result)
})
})
const week = [
{id: 1, day: 1},
{id: 2, day: 2},
{id: 3, day: 3},
{id: 4, day: 4},
{id: 5, day: 5},
{id: 6, day: 6},
{id: 7, day: 7},
]
const diet = week
.map(value => ({
id: value.id,
day: value.day,
meals: [
returnResultOfQuery(),
returnResultOfQuery(),
returnResultOfQuery()
]
}))
console.log(diet)
答案 0 :(得分:0)
实现此目的的一种方法是,首先使用Promise.all
执行所有查询,一旦获得结果,就创建一个新对象。像这样:
const week = [
{ id : 1, day : 1 },
{ id : 2, day : 2 },
{ id : 3, day : 3 },
{ id : 4, day : 4 },
{ id : 5, day : 5 },
{ id : 6, day : 6 },
{ id : 7, day : 7 }
];
const returnResultOfQuery = () => {
return Dinner1300.count ().exec ( function ( err, count ) {
const random = Math.floor ( Math.random () * count );
return Dinner1300.findOne ().skip ( random ).exec (
function ( err, result ) {
console.log ( result );
return result;
} );
} );
};
let promises = [];
for ( let x in week ) {
promises.push ( returnResultOfQuery () );
promises.push ( returnResultOfQuery () );
promises.push ( returnResultOfQuery () );
}
let diet = [];
Promise.all ( promises ).then ( function ( result ) {
let i = 0;
for ( let x in week ) {
diet.push (
{
id : x.id,
day : x.day,
meals : [
result[ i ],
result[ i + 1 ],
result[ i + 2 ]
]
}
);
i = i + 3;
}
} );
console.log ( diet );
附言:我尚未测试以上代码。
答案 1 :(得分:0)
您可以使用代码,这只是承诺包装器
const returnResultOfQuery = () => {
return new Promise((resolve, reject) => {
Dinner1300.count().exec(function (err, count) {
const random = Math.floor(Math.random() * count)
Dinner1300.findOne().skip(random).exec(
function (err, result) {
if (err) {
return reject(err);
}
return resolve(result);
});
});
});
}
const week = [
{id: 1, day: 1},
{id: 2, day: 2},
{id: 3, day: 3},
{id: 4, day: 4},
{id: 5, day: 5},
{id: 6, day: 6},
{id: 7, day: 7},
]
const diet = Promise.all(week
.map(value => ({
id: value.id,
day: value.day,
meals: [
returnResultOfQuery(),
returnResultOfQuery(),
returnResultOfQuery()
]
}))
);
console.log(diet)