将Promise.all([承诺列表])转换为ramda

问题描述 投票:1回答:3

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

对于例如

// 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或其他东西?有人可以推荐吗?

javascript ramda.js
3个回答
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();

1
投票

我认为你的意思是使用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

0
投票

我会尝试这样的事情:

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))这样的东西一旦你习惯它就会读得很好。我尽量不接受承诺作为参数。

© www.soinside.com 2019 - 2024. All rights reserved.