为什么这个承诺会解决链中的第一项而不是最后一项?

Why does this promise resolve with the first item in the chain instead of the last one?

我试图通过在业余项目中使用它们来更好地理解承诺,但我不明白为什么它从承诺链的第一个 .then 而不是最后一个中获取值。换句话说,我如何 运行 承诺中的一些任意代码,然后在最后 return 该承诺之外的值?谢谢!我期望值 'x' 但程序 returns 'b'.

var Promise = require('bluebird')

Promise.resolve('x')
  .then(function (user) {
    return Promise.resolve('c').then(function (roll) {
      return Promise.resolve('a').then(function (user) {
        return Promise.resolve('b')
      })
      .then(Promise.resolve('x'))
    })
  })
  .then(function (output) {
    console.log(output)
  })

我相信一个承诺只能解决一次。其余的将被忽略。通过链接 thens 来实现解析值的进一步突变。要获得您正在寻找的结果(x 的输出),您的代码将是:

    var Promise = require('bluebird')

Promise.resolve('x')
  .then(function (doesnotmatter) {
    return Promise.resolve('c').then(function (alsodoesnotmatter) {
      return Promise.resolve('a').then(function (noneofthismatters) {
        return Promise.resolve('b')
      })
      .then(function(){return 'x'})
    })
  })
  .then(function (output) {
    console.log(output) // 'x'
  })

为了让例子更清楚:

var Promise = require('bluebird')

Promise.resolve('y')
  .then(function (y) {
    // y == 'y'
    return 'c';
  })
  .then(function(c) {
    // c == 'c'
    return 'a';
  })
  .then(function(a) {
    // a == 'a'
    return 'b';
  })
  .then(function(b) {
    // b == 'b'
    return 'x';
  }).
  then(function(x) {
    console.log(x);  // output is 'x';
  });

承诺链的要点在于它允许 then 回调来转换结果,这就是您所看到的。如果您不想转换结果,则必须return您的then回调接收到的值才能传播它,或者继续使用原始值promise 而不是使用由 then.

编写的 return

请记住,then 创建了 一个承诺,它是根据您从 then 回调中 return 得到的。因此,即使不是全部,也不需要大多数 Promise.resolve 调用。

几个简单的例子(需要浏览器 Promise 支持):

// Prints:
//    First callback got a
//    Second callback got A
Promise.resolve("a")
  .then(function(value) {
    console.log("First callback got " + value);
    return value.toUpperCase();
  })
  .then(function(value) {
    console.log("Second callback got " + value);
    return value.toUpperCase();
  });

// Contrast that with using the same promise for both `then` calls:
// Prints:
//    Third callback got a
//   Fourth callback got a
setTimeout(function() {
  var p = Promise.resolve("a");
  p.then(function(value) {
    console.log("Third callback got " + value);
    return value.toUpperCase();
  });
  p.then(function(value) {
    console.log("Fourth callback got " + value);
    return value.toUpperCase();
  });
}, 100);