如何在承诺链中使用相同的价值?

How to use the same value in a promise chain?

_stats.value() 本身就是一个已解决的承诺。许多方法都需要它,如下所示。所有这些方法都接受 _stats 作为参数。

为简单起见,我只使用方法名称,不在函数内部调用函数从方法返回_stats

我想通过删除 .return 个调用来简化它

return Promise.resolve()
  .then(removeYesterdayKeys)
  .then(renameTodayKeys).return(_stats.value())
  .then(removeStatsOfToday).return(_stats.value())
  .then(addStatsOfToday).return(_stats.value())
  .tap(console.log.bind(console))

您可以将多个 .then 附加到一个承诺:

var p = Promise.resolve('foo');
p.then(bar);
p.then(baz);

barbaz 都将收到 'foo' 作为它们的参数。

但是,链接到 .then 意味着下一个函数将接收前一个 .then 的输出作为参数:

p.then(bar).then(baz);

baz 收到任何东西 bar returns.

这就是它的工作方式,选择对您的情况有用的一种。也许在其中执行 barbaz 的单个回调最有用? Promise 只应该解决 异步 执行问题;不要仅仅因为链条看起来不错就将它们用于同步代码。

如果你不想.return()调用,也不想改变你的方法,你唯一的选择是传递函数表达式:

return _stats.value().then(function(stats) {
    return removeYesterdayKeys()
      .then(renameTodayKeys)
      .then(function(_) { return removeStatsOfToday(stats); })
      .then(function(_) { return addStatsOfToday(stats); })
      .then(function(_) { console.log(stats); return stats; });
});

或者,更接近您的原始示例,但不一定更好:

return removeYesterdayKeys()
  .then(renameTodayKeys)
  .then(function(_) { return _stats.value().then(removeStatsOfToday); })
  .then(function(_) { return _stats.value().then(addStatsOfToday; })
  .then(function(_) { return _stats.value().tap(console.log.bind(console)) });

如果您正在寻找一种真正优雅的方式,您当然应该看一看 async/await 提案(及其实验性实施)。

实际上,使用下划线你可以这样做:

var feedStatsTo = function(f) { return _.partial(f, statsOfToday); };

return Promise.resolve()
  .then(removeYesterdayKeys)
  .then(renameTodayKeys)

  .then(feedStatsTo(removeStatsOfToday))
  .then(feedStatsTo(addStatsOfToday))

  .return(statsOfToday)
  .tap(console.log.bind(console))