【问题标题】:Convert Promise.all([list of promises]) to ramda将 Promise.all([list of promises]) 转换为 ramda
【发布时间】:2017-04-25 06:29:20
【问题描述】:

我编写了一个函数,它返回一个承诺列表(ramda 中的代码),然后我必须用 Promise.all() 将其包围以解决所有承诺并将其发送回承诺链。

例如

// Returns Promise.all that contains list of promises. For each endpoint we get the data from a promised fn getData().
const getInfos = curry((endpoints) => Promise.all(
  pipe(
    map(getData())
  )(endpoints))
);

getEndpoints()   //Get the list of endpoints, Returns Promise
  .then(getInfos) //Get Info from all the endpoints
  .then(resp => console.log(JSON.stringify(resp))) //This will contain a list of responses from each endpoint

promiseFn 是返回 Promise 的函数。

我怎样才能最好地将这个函数转换成完整的 Ramda 类,并使用 pipeP 或其他东西?有人可以推荐吗?

【问题讨论】:

  • 你能更详细地解释一下这是做什么的,也许用更明确的变量名?例如,外部pipe 做什么?它看起来无关紧要。 promiseFn 是做什么的?
  • @ScottSauyet 我已经更新了问题,如果您需要更多信息,请告诉我。谢谢
  • 我不明白你所说的“打破了使用柯里化函数的想法”是什么意思
  • @geek 所以你想避免使用const 声明、初始化器、箭头函数、参数,使用Promise.all,函数调用,使用getData?这些都不是 Ramda 的一部分。
  • @Bergi:这并不是 Ramda 没有等价物的原因。事实上,我们有许多原生方法的纯函数等价物。我们很少处理 Promises,因为没有一个作者非常喜欢 Promise,而是更喜欢更合法的类型,例如 Futures 或 Tasks。

标签: javascript ramda.js


【解决方案1】:

不确定你想要达到什么,但我会这样重写它:

const getInfos = promise => promise.then(
  endpoints => Promise.all(
    map(getData(), endpoints)
  )
);

const log = promise => promise.then(forEach(
  resp => console.log(JSON.stringify(resp))
));

const doStuff = pipe(
  getEndpoints,
  getInfos,
  log
);

doStuff();

【讨论】:

    【解决方案2】:

    我想你的意思是使用pointfree notation

    我建议使用compose。使用ramda 时这是一个很棒的工具。

    const getInfos = R.compose(
      Promise.all,
      R.map(getData),
    );
    
    // Now call it like this.
    getInfos(endpoints)
      .then(() => console.log('Got info from all endpoints!'));
    
    // Because `getInfos` returns a promise you can use it in your promise chain.
    getEndpoints()
      .then(getInfos) // make all API calls
      .then(R.map(JSON.stringify)) // decode all responses
      .then(console.log) // log the resulting array
    

    【讨论】:

      【解决方案3】:

      我会尝试这样的:

      const getEndpoints = () =>
        Promise.resolve(['1', '2', '3', '4', '5', '6', '7', '8'])
      const getEndpointData = (endpoint) =>
        Promise.resolve({ type: 'data', endpoint })
      
      const logEndpointData = pipe(
        getEndpoints,
        then(map(getEndpointData)),
        then(ps => Promise.all(ps)),
        then(console.log)
      )
      
      logEndpointDatas()
      

      我犹豫是否仅将 2 个功能与 pipe / compose 结合起来。一旦你习惯了,像then(map(callback)) 这样的东西就会很好读。而且我尽量不将承诺作为参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-28
        • 2015-09-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多