1

The use case is: I have an event handler that does some processing. It calls a function which returns a promise. I need a guarantee that the function eventually completes or fails, however, I do not need to do any additional processing afterwards. This appears to work but it looks like bad practice:

function onMyEvent() {
  return promisifiedFunction()
  .catch( //log error );
}
function someFunction() {
  emit(‘myevent’);
}

Is this bad practice to have catch without then? It seems to work fine.

I did not think I needed a return either as I could fire-and-forget but I think it's needed if I want to catch the error

cppNoob
  • 422
  • 1
  • 5
  • 17
  • Both 1. having only a `catch` and 2. not using a `return` is perfectly fine and not bad practice. As a matter of fact, adding a `then` or a `return` when they are not needed could be considered bad practice since its could lead to confusing code. – nem035 Nov 07 '16 at 19:55
  • Does this answer your question? [How does Promise run when .then method is not called?](https://stackoverflow.com/questions/51431235/how-does-promise-run-when-then-method-is-not-called) – King Holly Aug 06 '21 at 20:23

1 Answers1

0

With a promise, using .then or .catch runs the promise. Or at least starts running it. A .catch function is just a different path for the Promise, namely when an exception occurs.

If you run a promise without a .then, the promise will resolve silently and could still enter .catch functions.

If you run a promise without a .catch, all .then functions still work/chain, and any exceptions will throw.

What you are doing is OK, and you may not even need the return statement, if you do not care about the result or are not chaining the promise.

clay
  • 5,917
  • 2
  • 23
  • 21
  • 3
    *"using .then or .catch runs the promise."* is not correct. Creating the promise itself is what runs it. Calling `then` or `catch` only attaches callbacks for promise resolutions – nem035 Nov 07 '16 at 19:52