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

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

我写了一个函数,其中 returns 一个承诺列表(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 是 returns 一个 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();

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

我会尝试这样的事情:

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)) 之类的东西读起来就很好。而且我尽量不把promises当作参数。