简体   繁体   中英

Promise/A+ with chain then() callbacks use case?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM