0
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?

Joss Bird
  • 295
  • 1
  • 4
  • 19
  • 2
    What sort of thing does `.collection` return? How's it intended to be used? – CertainPerformance Apr 23 '20 at 10:10
  • 1
    Or, does your current code work, but you want to avoid the `callback` part of it and have the consumer use the returned Promise instead? – CertainPerformance Apr 23 '20 at 10:12
  • @CertainPerformance It's a mongodb collection, but it could be any variable that will become out of scope after `client.close()` is called. It's more of a general JavaScript query. My current code works I want to avoid the callback element – Joss Bird Apr 23 '20 at 10:12
  • So, do you just want this: [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784) – VLAZ Apr 23 '20 at 10:26
  • @VLAZ No because I want to do stuff inside of my API after calling my callback which none of the answers in there seem to do. – Joss Bird Apr 23 '20 at 10:29

1 Answers1

1

Returning a plain Promise won't work here, because a plain Promise is mostly indifferent to the .thens that may be called on it later. All that a Promise can do with .thens 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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320