简体   繁体   English

将Promise.all([promise of list])转换为ramda

[英]Convert Promise.all([list of promises]) to ramda

I have written a function which returns a list of promises (code in ramda), and I then have to surround that with Promise.all() to resolve all promises and sends it back to promise chain. 我编写了一个函数,该函数返回一个Promise列表(以ramda表示的代码),然后必须用Promise.all()将其包围起来,以解决所有Promise并将其发送回Promise链。

For eg 例如

// 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 is the function that returns a Promise. promiseFn是返回Promise的函数。

How can I best convert this function into complete Ramda like, and use of either pipeP or something else? 我怎样才能最好地将此函数转换为完整的Ramda之类的东西,并使用pipeP或其他东西? Can someone recommend? 有人可以推荐吗?

Not sure what you want to achieve, but I would rewrite it like that : 不知道要实现什么,但是我会这样重写它:

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();

I think you mean using pointfree notation . 我认为您的意思是使用无点表示法

I'd recommend using compose . 我建议使用compose It's a great tool when using ramda . 使用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

I'd try something like this: 我会尝试这样的事情:

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()

I hesitate to combine just 2 functions with pipe / compose. 我犹豫是否只将2个函数与pipe / compose结合使用。 Things like then(map(callback)) reads fine once you get used to it. 一旦习惯了, then(map(callback))东西就可以正常阅读了。 And I try not to take promises as parameters. 而且,我尽量不要将诺言作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM