我的问题是如何在节点J中编写嵌套循环
我的代码
var result = db.data;
var FirstArray= new Array();
var SecondArray= new Array();
GetUserData();
async function GetUserData(){
for (let info of result) {
await getUserInfo(info);
}
res.send({status:"True", data: FirstArray, newdata:SecondArray });
}
function getUserInfo(info){
return new Promise(( resolve, reject )=>{
UserModel.UserType.findOne({'_id': info.UserId }, usersProjection, function(err, UserData) {
if(err) {
res.send({status:"Fale", Error:err });
reject(err);
} else {
var data = UserData;
FirstArray.push(data);
GetUser();
async function GetUser(){
for (let newinfo of data ) {
await getnewUserInfo(newinfo);
}
}
function getnewUserInfo(newinfo){
return new Promise(( resolve, reject )=>{
UserModel.UserTypeNew.findOne({'_id': newinfo.UserId }, usersProjection, function(newerr, UserData) {
if(newerr) {
res.send({status:"Fale", Error:newerr });
reject(err);
} else {
SecondArray.push(UserData)
resolve();
}
});
});
}
}
});
});
}
我将获得第一个循环细节,如何获取第二个循环细节。
建议另一种方法。
然后哪种方法是嵌套循环的最佳实践。
答案 0 :(得分:1)
因为猫鼬应该返回承诺,所以你不需要新的承诺。您可以使用map将数据映射到promises,然后使用Promise.all
等待它们同时执行。您当前的代码逐个执行查询(如果当前完成,则仅执行下一个查询)。这不是必需的,也很慢。
因此,您可以将db.data
映射到[[first,second],[first,second],...]
。我没有映射findOne
的结果,因为它不应该返回数组,并且发现something of resultOfFindOne
实际上有效,因为findOne应该返回一个文档或null。
UserModel.UserType.findOne
和UserModel.UserTypeNew.findOne
都尝试按_id
查找一条记录,并且都使用相同的_id
,因此无需进行UserType查询,然后返回执行UserTypeNew查询,您只需使用info.UserId
进行查询。
const GetUserData = (result) =>
Promise.all(
result.map(info=>getUserInfo(info))
).then(
results=>{//results should be [[first,second],[first,second],...]
let [FirstArray,SecondArray] = results.reduce(
([allFirst,allSecond],[first,second])=>
[allFirst.concat([first]),allSecond.concat([second])],
[[],[]]
);
res.send({ status: "True", data: FirstArray, newdata: SecondArray })
}
).catch(
err=>
res.send({status:"Fale", Error:err })
);
const getUserInfo = info =>
//mongoose can return promises, no need to convert callback api to promise:
//http://mongoosejs.com/docs/queries.html
Promise.all([
UserModel.UserType.findOne({ '_id': info.UserId }, usersProjection).exec(),
UserModel.UserTypeNew.findOne({ '_id': info.UserId }, usersProjection).exec()
]);
//when using const the function is not hoisted so you can't call a function
// before it was declared.
GetUserData(db.data);
如果您使用的是旧版本的mongoose(不是5.xxx),您可能仍需要将基于回调的api转换为promises,它看起来有点像这样:
const asPromise = object => fn => args =>
new Promise(
(resolve,reject)=>
fn.apply(
object,
args.concat([
(...result)=>
(result[0])//first argument of callback is error
? reject(result[0])//reject with error
: resolve(result.slice(1,result.length))//resolve with result(s)
])
)
);
const newUserType = asPromise(UserModel.UserTypeNew);
const userType = asPromise(UserModel.UserType);
//making a query with callback but convert it to promise
newUserType(UserModel.UserTypeNew.findOne)([
{ '_id': info.UserId }, usersProjection
]).then(//this will resolve as array, only need first item
([result])=>result
);
userType(UserModel.UserType.findOne)([//note that I'm not passing UserModel.UserTypeNew.findOne
{ '_id': info.UserId }, usersProjection
]).then(//this will resolve as array, only need first item
([result])=>result
);
答案 1 :(得分:0)
<div>
{ this.state.lon && this.state.lat && <Fetch lon={this.state.lon} lat={this.state.lat} /> }
</div>
最后,我将获得解决方案
感谢所有