mongoose 如何重写代码(使用多个顺序/依赖promise)而不嵌套await调用

zqdjd7g9  于 2023-10-19  发布在  Go
关注(0)|答案(1)|浏览(100)

我在写一个测试案例。在清理期间,测试用例应该
1.删除所有收藏
1.确认已删除集合
1.重新创建收藏
据我所知,createCollectiondropCollection返回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}`);
      });
    })
  })
});
8gsdolmq

8gsdolmq1#

你可以在回调函数体中等待。你只需要将回调函数声明为一个callback函数:

const collectionsBeforeDrop = await db.collections();
collectionsBeforeDrop.forEach(async (c) => {
    console.log(`got collection name : ${c.collectionName}`);
    await db.dropCollection(c);
});

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(async (c) => {
    console.log(`got collection name : ${c.collectionName}`);
    await db.createCollection(c)
        .then(async () => {
            console.log(`checking after recreating collections`)
            await db.collections()
                .then((collectionsAfterRecreation) => {
                    collectionsAfterRecreation.forEach(c => {
                        console.log(`got collection name after claanup! THIS SHOULDN'T HAVE HAPPENED : ${c.collectionName}`);
                    });
                })
        })
});

未经测试,可能需要调整。

相关问题