1

I just started reading about Promise/A+ and wanted to try it for myself. I added multiple then() callbacks and this behavior was surprising.

1) Chaining the then doesn't return the same promise

  > new Promise(function(a, r) {a('hello')}).
      then(function(r) { console.log('1', arguments) }).
      then(function(r) { console.log("2", arguments) })
  1 ["hello"]
  2 [undefined]

2) Not-chaining works as I expected

> p = new Promise(function(a, r) {a('hello')}); 
    p.then(function(r) { console.log('1', arguments) }); 
    p.then(function(r) { console.log("2", arguments) })
1 ["hello"]
2 ["hello"]

What is the use case for scenario #1?

hakunin
  • 4,041
  • 6
  • 40
  • 57
  • 1
    The return value of the `then` method is the [most important promise feature](http://stackoverflow.com/a/22562045/1048572)! – Bergi Mar 03 '16 at 09:09
  • 2
    Instead of asking for example use cases of chaining, let's turn the tables: Give me an example use case for promises, and I'll show you why you need to use chaining for it. – Bergi Mar 03 '16 at 09:11
  • @Bergi, so, possibly close this question as duplicate? – Grundy Mar 03 '16 at 09:13
  • @Grundy: I didn't consider it a duplicate. Can you recommend a target? – Bergi Mar 03 '16 at 09:14
  • @Bergi, i thought about question in your comment above, because seems here same common question about promises – Grundy Mar 03 '16 at 09:17
  • @Grundy: Feel free to cast your vote :-) – Bergi Mar 03 '16 at 09:21
  • Possible duplicate of [Aren't promises just callbacks?](http://stackoverflow.com/questions/22539815/arent-promises-just-callbacks) – Grundy Mar 03 '16 at 09:28
  • @Bergi I wasn't saying it isn't useful, I just wanted to know where you would use it. Also I didn't know you were able to return value from the first `then()` to the next one, thats pretty cool. – hakunin Mar 03 '16 at 10:07

1 Answers1

2

You just should return value from promise.

new Promise(function(a, r) {a('hello')}).
      then(function(r) { 
        console.log('1', arguments);
        return r; 
      }).
      then(function(r) { console.log("2", arguments) })

The returned value passed as argument to callback in then function.

Grundy
  • 13,356
  • 3
  • 35
  • 55
  • Thanks for pointing that out, but I had to read your answer 3 times carefully, can you improve it a bit so others can benefit too? – hakunin Mar 03 '16 at 10:03
  • @hakunin, i not quite understand how exactly i should improve it, can you a bit explain it? – Grundy Mar 03 '16 at 10:05
  • "You just should return value from promise." isn't very descriptive. The code formatting is also all over the place and you're missing the output as well. – hakunin Mar 03 '16 at 10:06