简体   繁体   English

Promise / A + with chain then()回调用例?

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

I just started reading about Promise/A+ and wanted to try it for myself. 我刚刚开始阅读有关Promise / A +的文章,并想亲自尝试一下。 I added multiple then() callbacks and this behavior was surprising. 我添加了多个then()回调,这种行为令人惊讶。

1) Chaining the then doesn't return the same promise 1)链接then不会返回相同的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 2)非链接按预期工作

> 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? 方案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. 返回的值作为参数传递给then函数中的回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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