如何在promise链中使用相同的值?

时间:2016-02-17 15:21:23

标签: javascript promise bluebird

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

为了简单起见,我只使用方法名称,而不调用函数 OR 中的函数从函数返回_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))

3 个答案:

答案 0 :(得分:0)

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

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

barbaz都会收到'foo'作为参数。

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

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

baz会收到bar次返回的内容。

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

答案 1 :(得分:0)

如果您不想要.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)) });

如果您正在寻找一种非常优雅的方式,您当然应该看一下异步/等待提议(及其实验性实施)。

答案 2 :(得分:0)

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

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))
相关问题