繁体   English   中英

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

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

我编写了一个函数,该函数返回一个Promise列表(以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或其他东西? 有人可以推荐吗?

不知道要实现什么,但是我会这样重写它:

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

我认为您的意思是使用无点表示法

我建议使用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

我会尝试这样的事情:

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))东西就可以正常阅读了。 而且,我尽量不要将诺言作为参数。

暂无
暂无

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

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