Client.close() not closing all connections when using Promise.all

I have the following script, where I drop two collections and then insert some data:

    const client = new MongoClient(uri); 
    const db = client.db("main");

    const listings = db.collection<Listing>("listings");
    const users = db.collection<User>("users");

    await Promise.all([listings.drop(), users.drop()]);
    await Promise.all([listings.insertMany(listingsData), users.insertMany(usersData)]);

    await client.close();

The thing is event after calling client.close() the script just hangs there, and I can´t do a clean exit.

But if I, instead, await for each promise separately, like this:

    const client = new MongoClient(uri); 
    const db = client.db("main");

    const listings = db.collection<Listing>("listings");
    const users = db.collection<User>("users");

    await listings.drop();
    await users.drop();
    await listings.insertMany(listingsData);
    await users.insertMany(usersData);

    await client.close();

Then it works as expected and the script just finish without the need of doing ctrl-z. Why is that?

I’m using node v18.12.1 and the mongodb node driver v4.12.0.

1 Like