使用ramda处理承诺并等待

时间:2017-10-12 06:18:03

标签: javascript arrays json ramda.js

我有一段代码由lodash编写,如下所示:

subscribeOn

我想把它改成ramda,经过几次思考并阅读一些Doc我写下面的代码:

observeOn

当然是错误的,不起作用,但它的第一种方法,我想知道如何使用ramda完美和功能性地处理这种情况。我怎么能这样做? order对象也是以下示例的数组:

downstream

}

1 个答案:

答案 0 :(得分:4)

我认为这是打破原始功能正在做什么的良好开端

const profit =
  price - // subtract the result
  _.sumBy(
    await Promise.all(
      // Wait for upstreamOrders to resolve, and grab the 'invoice'
      // key for each
      map(uOrder => uOrder.invoice, await order.upstreamOrders),
    ),
    // calculate the sum of the invoices, based on the 'amount' key
    'amount',
  );

考虑到这一点,我们可以分解这些步骤,并将计算(同步)与数据分离(异步)

Ramda没有sumBy,因为我们可以从其他函数中创建它。如果你将其细分,我们所做的就是在两个不同的地方抓住invoiceamount,但我们可以通过

获取一系列金额
map(path(['invoice', 'amount']))

我们可以将其放在sumsubtract旁边,以创建一个完全独立于我们的异步代码的函数

const calculateProfits = (price, orders) => compose(
  subtract(price),
  sum,
  map(path(['invoice', 'amount'])),
)(orders)

允许我们做类似的事情:

const profit = calculateProfits(price, await order.upstreamOrders)

或者calculateProfits是否已经过咖喱(并且我不确定上游订单是如何工作的,是否是一个返回承诺的吸气剂?)

const getUpstreamOrders = order => order.upstreamOrders

getUpstreamOrders(order)
  .then(calculateProfits(price))
  .then(profits => {
    // Do what you want with the profits
  })

最后,关于初始尝试的一些注释

const result = R.compose(
  R.pick(['amount']),

  // Promise.all is being called without any arguments
  // it doesn't really fit within `compose` anyway, but if we were
  // feeding an array of promises through, we'd want to just
  // put `Promise.all,`
  await Promise.all(),

  // the arguments here should be the other way around, we're
  // mapping over upstreamOrders, and the data comes last
  // uOrder isn't available in this scope, previously it was
  // `uOrder => uOrder.invoice`,
  // invoking a function and returning the invoice for that order
  R.map(await order.upstreamOrders, uOrder.invoice),
);