Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Wait对collection.insertMany()工作不正常?_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript Wait对collection.insertMany()工作不正常?

Javascript Wait对collection.insertMany()工作不正常?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我试图用collection.insertMany()在我的集合中插入许多记录,并对其进行了测试,但不幸的是,此测试不是确定性的(await有时有效,有时无效)。为什么我会这样想,因为collection.insertMany('Inserted ten rogues in collection')有时会在console.log(queryResult)之后显示空数组,这会导致我的测试有时失败有时通过。为什么这个等待有时有效有时无效 我的测试: description('保存记录',()=>{

我试图用
collection.insertMany()
在我的集合中插入许多记录,并对其进行了测试,但不幸的是,此测试不是确定性的(await有时有效,有时无效)。为什么我会这样想,因为
collection.insertMany('Inserted ten rogues in collection')
有时会在
console.log(queryResult)
之后显示空数组,这会导致我的测试有时失败有时通过。为什么这个等待有时有效有时无效

我的测试:

description('保存记录',()=>{
它('Save single record in DB',async()=>{
const warrior1=新战士({
姓名:'约翰',
班级:'牧师',
年龄:21岁,
体重:75
});
等待warrior1.save();
断言(warrior1.isNew==false);
});
它('在数据库中保存多条记录',异步()=>{
const tenRogues=createnRouges();
等待战士。收集。插入许多(十个盗贼,(呃,_文档)=>{
如果(错误){
控制台错误(err);
}否则{
log('在集合中插入了十个盗贼');
}
});
const queryResult=wait Warrior.find({class:'rogue'});
console.log(queryResult);
断言(queryResult.length==10);
});
});
CreateTenRogues方法:

函数createnRouges(){
常数战士=[];
for(设i=0;i<10;i++){
战士,推(新战士)({
姓名:'约翰',
职业:'流氓',
年龄:21岁,
体重:75
}));
}
返回战士;
}

如果在
insertMany()
调用中使用回调函数,该函数将不会返回
承诺
,因此使用
等待
没有任何作用

假设您希望在回调上使用
async/await
,您可以使用
try/catch
块进行错误检查,然后
await
将正常工作:

试试看{
等待战士。收集。插入许多(十盗贼);
log('在集合中插入了十个盗贼');
}捕捉(错误){
控制台错误(err);
}

很抱歉,但我的测试有时仍然通过,有时不通过:/test-after-changes:`it('Save multi-records in-DB',async()=>{const-tenRogues=createTenRouges();try{wait-Warrior.collection.insertMany(tenRogues);console.log('Inserted-tenRogues in-collection');}catch(err){console.log(err)}const queryResult=await Warrior.find({class:'rogue'});assert(queryResult.length==10);};“``你的
createnRogues()
函数返回什么?如果它是
承诺
你也需要
等待
这个。不,它是非常简单的函数(不是异步的),但如果你想看到这个函数,我可以添加到问题中?嗯,它是wierd,但现在(可能在10分钟后)我重新运行这个测试大约30次,它一直通过,我不知道为什么它不能立即工作,但它现在似乎工作了。谢谢你的回答