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

标签 javascript promise es6-promise

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

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) 非链接工作如我所料

> 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 的用例是什么?

最佳答案

您只需从 promise 中返回值即可。

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

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

关于javascript - Promise/A+ with chain then() 回调用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35766947/

相关文章:

javascript - 如何将变量传递给 Promise 链中调用的另一个文件中的异步函数

javascript - 使用具有递归函数的 promise

javascript - 如何实现重复的 Promise 调用链?

javascript - 异步读取数据库返回集合

javascript - 动态表单 + javascript

javascript - jquery:在div中加载html页面

javascript - 当函数需要访问外部范围变量时处理 Promise 流的更好方法

javascript - 使用 Javascript 刷新 div 的问题

javascript - 使用js制作一个div幻灯片

javascript - Calendar.events.lists 回调参数不会被调用