我在写一个测试案例。在清理期间,测试用例应该
1.删除所有收藏
1.确认已删除集合
1.重新创建收藏
据我所知,createCollection
和dropCollection
返回Promises
-https://mongoosejs.com/docs/api/connection.html#Connection.prototype.dropCollection()
我想等待Promises
按顺序完成。我想我会使用await
,但我不能嵌入await
s。我如何重写代码?
const collectionsBeforeDrop = await db.collections();
collectionsBeforeDrop.forEach(c => {
console.log(`got collection name : ${c.collectionName}`);
await db.dropCollection(c); <-- can't use await here
});
console.log(`checking after cleanup`)
const collectionsAfterDrop = await db.collections();
collectionsAfterDrop.forEach(c => {
console.log(`got collection name after claanup! THIS SHOULDN'T HAVE HAPPENED : ${c.collectionName}`);
throw new Error("couldn't clean up after test case");
});
console.log(`creating collections again`);
collectionsBeforeDrop.forEach(c => {
console.log(`got collection name : ${c.collectionName}`);
await db.createCollection(c) <-- can't use await unless at top level
.then(()=>{
console.log(`checking after recreating collections`)
await db.collections() <-- can't use await unless at top level
.then((collectionsAfterRecreation)=>{
collectionsAfterRecreation.forEach(c => {
console.log(`got collection name after claanup! THIS SHOULDN'T HAVE HAPPENED : ${c.collectionName}`);
});
})
})
});
1条答案
按热度按时间8gsdolmq1#
你可以在回调函数体中等待。你只需要将回调函数声明为一个callback函数:
未经测试,可能需要调整。