Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is .then(success, fail) considered an antipattern for promises?

People also ask

How do you wait for promises to complete?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

What function will return as soon as the first promise is either fulfilled or rejected?

race() , which returns the first settled value (either fulfillment or rejection), this method returns the first fulfilled value.

Does promise all wait?

Using Promise. all. Promise. all waits for all fulfillments (or the first rejection).


What's the difference?

The .then() call will return a promise that will be rejected in case the callback throws an error. This means, when your success logger fails, the error would be passed to the following .catch() callback, but not to the fail callback that goes alongside success.

Here's a control flow diagram:

control flow diagram of then with two argumentscontrol flow diagram of then catch chain

To express it in synchronous code:

// some_promise_call().then(logger.log, logger.log)
then: {
    try {
        var results = some_call();
    } catch(e) {
        logger.log(e);
        break then;
    } // else
        logger.log(results);
}

The second log (which is like the first argument to .then()) will only be executed in the case that no exception happened. The labelled block and the break statement feel a bit odd, this is actually what python has try-except-else for (recommended reading!).

// some_promise_call().then(logger.log).catch(logger.log)
try {
    var results = some_call();
    logger.log(results);
} catch(e) {
    logger.log(e);
}

The catch logger will also handle exceptions from the success logger call.

So much for the difference.

I don't quite understand its explanation as for the try and catch

The argument is that usually, you want to catch errors in every step of the processing and that you shouldn't use it in chains. The expectation is that you only have one final handler which handles all errors - while, when you use the "antipattern", errors in some of the then-callbacks are not handled.

However, this pattern is actually very useful: When you want to handle errors that happened in exactly this step, and you want to do something entirely different when no error happened - i.e. when the error is unrecoverable. Be aware that this is branching your control flow. Of course, this is sometimes desired.


What's wrong with the following?

some_promise_call()
.then(function(res) { logger.log(res) }, function(err) { logger.log(err) })

That you had to repeat your callback. You rather want

some_promise_call()
   .catch(function(e) {
       return e; // it's OK, we'll just log it
   })
   .done(function(res) {
       logger.log(res);
   });

You also might consider using .finally() for this.


The two aren't quite identical. The difference is that the first example won't catch an exception that's thrown in your success handler. So if your method should only ever return resolved promises, as is often the case, you need a trailing catch handler (or yet another then with an empty success parameter). Sure, it may be that your then handler doesn't do anything that might potentially fail, in which case using one 2-parameter then could be fine.

But I believe the point of the text you linked to is that then is mostly useful versus callbacks in its ability to chain a bunch of asynchronous steps, and when you actually do this, the 2-parameter form of then subtly doesn't behave quite as expected, for the above reason. It's particularly counterintuitive when used mid-chain.

As someone who's done a lot of complex async stuff and bumped into corners like this more than I care to admit, I really recommend avoiding this anti-pattern and going with the separate handler approach.


By looking at advantages and disadvantages of both we can make a calculated guess as to which is appropriate for the situation. These are the two main approaches to implementing promises. Both have it's pluses and minus

Catch Approach

some_promise_call()
.then(function(res) { logger.log(res) })
.catch(function(err) { logger.log(err) })

Advantages

  1. All errors are handled by one catch block.
  2. Even catches any exception in the then block.
  3. Chaining of multiple success callbacks

Disadvantages

  1. In case of chaining it becomes difficult to show different error messages.

Success/Error Approach

some_promise_call()
.then(function success(res) { logger.log(res) },
      function error(err) { logger.log(err) })

Advantages

  1. You get fine grained error control.
  2. You can have common error handling function for various categories of errors like db error, 500 error etc.

Disavantages

  1. You will still need another catch if you wish to handler errors thrown by the success callback

Simple explain:

In ES2018

When the catch method is called with argument onRejected, the following steps are taken:

  1. Let promise be the this value.
  2. Return ? Invoke(promise, "then", « undefined, onRejected »).

that means:

promise.then(f1).catch(f2)

equals

promise.then(f1).then(undefiend, f2)

Using .then().catch() lets you enable Promise Chaining which is required to fulfil a workflow. You may need to read some information from database then you want to pass it to an async API then you want to manipulate the response. You may want to push the response back into the database. Handling all these workflows with your concept is doable but very hard to manage. The better solution will be then().then().then().then().catch() which receives all errors in just once catch and lets you keep the maintainability of the code.