Javascript: Promises indentation

Created on 20 Jul 2016  路  3Comments  路  Source: airbnb/javascript

What do you prefer when writing promises?

caches.open('cache').then(function (cache) {
  cache.put(event.request, clonedResponse);
});

caches.open('cache')
  .then(function (cache) {
    cache.put(event.request, clonedResponse);
  });

Some things that could alter the answer could be the catch, i found the second one clearer when using catch, but i also find the first one more clear when catch is ommited. Also if the promise is long like: someObjectThatContains.someMethod(SomeVariable), chaining then in the same line can slip past the then method.

Anyway, Do you have preference?

question

Most helpful comment

The goal is readability and consistency, and occasionally one takes a small hit in favor of the other.

I suppose given those two I'd lean towards the former, but I don't think we have an official stance on it.

All 3 comments

In general, every promise chain should have a .catch on it to ensure errors are handled.

That said, I think either approach is fine, and it likely depends on the specific context.

So both of this are ok? That doesn't seem consistent :(

caches.open('cache').then(function (cache) {
  cache.put(event.request, clonedResponse);
}).catch(function(e) {
  //
};

caches.open('cache')
  .then(function (cache) {
    cache.put(event.request, clonedResponse);
  })
  .catch(function(e) {
    //
  });

(Btw ignore the other rules, i know i'm not using arrows, etc)

The goal is readability and consistency, and occasionally one takes a small hit in favor of the other.

I suppose given those two I'd lean towards the former, but I don't think we have an official stance on it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

olalonde picture olalonde  路  3Comments

weihongyu12 picture weihongyu12  路  3Comments

tpiros picture tpiros  路  3Comments

ryankask picture ryankask  路  3Comments

mismith picture mismith  路  3Comments