Reputation: 311
async function fetchUserCollection(callback)
{
await client.connect();
const userCollection = client.db('database').collection('users');
await callback(userCollection);
client.close();
}
I'm trying to move away from callbacks and towards Promises.
However await resolve(userCollection)
would not work here if this was a promise as resolve()
returns immediately.
Is there a way to use promises here? or is a callback necessary here?
Upvotes: 0
Views: 40
Reputation: 370989
Returning a plain Promise won't work here, because a plain Promise is mostly indifferent to the .then
s that may be called on it later. All that a Promise can do with .then
s called on it is to execute them once the Promise resolves, and that's it. Spec-compliant Promises don't have a functionality to run something after something finishes consuming them with .then
.
I think what you're doing currently is the cleanest solution there is. Despite the fact that Promises exist, callbacks aren't inherently bad - sometimes there are use cases for them, like here. The main issue with callbacks IMO is when they get nested in each other, and a lot of ugly indentation and hard-to-read code results, but that's not going on in your code.
Upvotes: 1