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

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

本文关键字:回调 调用 then with chain Promise      更新时间:2023-09-26

我刚开始阅读有关Promise/A +的文章,并想亲自尝试一下。我添加了多个then()回调,这种行为令人惊讶。

1)链接然后不会返回相同的承诺

  > 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)没有像我预期的那样链接工作

> 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"]

场景 #1 的用例是什么?

你只需要从承诺中返回值。

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

返回的值作为参数传递给函数中的回调then