[英]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.