5

Promises are a new addition to Javascript (ES6).

We can do promise chaining by appending the .then() handler to one another.

For example:


//Using MongoDB query as an example,

db.collection.findOne({id:userId})
.then()
.then()
.then()
.....
.catch(err)

So my question is how many .then() block can you have in total in a single promise?

I am thinking that perhaps it depends only on the system processing power limit. But I also wonder if there is any programmatic limitation imposed by Javascript.

5
  • as many as you need Commented Apr 27, 2020 at 9:54
  • 1
    @t.niese well, "chain hell" doesn't sound as well.
    – VLAZ
    Commented Apr 27, 2020 at 10:04
  • @VLAZ does not sound well is not really a reason to use a term, that is commonly used for the over-use of callback nesting, for another problem. If you search for callback hell you will find almost exclusively articles about nesting.
    – t.niese
    Commented Apr 27, 2020 at 10:12
  • @t.niese yes, the other problem for why it doesn't sound OK is that there isn't really a "chain hell".
    – VLAZ
    Commented Apr 27, 2020 at 10:14
  • @VLAZ that is not necessarily true, with chaining you sometimes have other problems (like the need of variables that are outside of the scope of the callback in the chain), which would lead to strange constructs and ugly code. So I wouldn't say there is no promise/chaining hell, as there are still some leftover problems the "callback hell" also had.
    – t.niese
    Commented Apr 27, 2020 at 10:26

2 Answers 2

10

There is no limit other than your memory, as each of them creates a new promise and a few callbacks. And notice that you are not chaining all the .then()s to a single promise, you are chaining each to the promise that the previous call returned.

8

The then method returns a Promise which allows for method chaining. When a value is simply returned from within a then handler, it will effectively return Promise.resolve(<value returned by whichever handler was called>). Hence, there is no limit. Source

Not the answer you're looking for? Browse other questions tagged or ask your own question.