[Ramda] Refactor a Promise Chain to Function Composition using Ramda
Promise chains can be a powerful way to handle a series of transformations to the results of an async call. In some cases, additional promises are required along the way. In cases where there are no new promises, function composition can reduce the number of dot chained thens you need. In this lesson, we'll look at how to take a promise chain, and reduce it down with function composition.
const deckUrl = 'https://deckofcardsapi.com/api/deck/new/shuffle/?cards=AS,2S,5C,3C,KD,AH,QH,2C,KS,8C'; fetch(deckUrl)
.then(res => res.json())
.then(deck => fetch(`https://deckofcardsapi.com/api/deck/${deck.deck_id}/draw/?count=10`)
.then(res => res.json())
.then(deck => deck.cards)
.then(cards => cards.filter(c => c.suit === 'CLUBS'))
.then(cards => cards.map(c => c.image))
.then(cards => cards.sort((c1, c2) => c1.value - c2.value)))
.then(cards => cards.map(u => `<img width="" src="${u}"/>`).join(''))
.then(imgString => {
document.querySelector('#cards').innerHTML = `<div>${imgString}</div>`
})
We want to use Ramda to improve code:
Using R.prop and R.map:
// from
.then(deck => deck.cards) // to
.then(prop('cards')) // from
.then(cards => cards.map(c => c.image)) //to
.then(map(prop('image')))
Using R.propEq and R.filter:
// from
.then(cards => cards.filter(c => c.suit === 'CLUBS')) //to
.then(filter(propEq('suit', 'CLUBS')))
Using R.sortBy:
// from
.then(cards => cards.sort((c1, c2) => c1.value - c2.value))) // to
.then(sortBy(prop('value'))))
Using R.compose:
// from
.then(cards => cards.map(u => `<img width="" src="${u}"/>`).join('')) // to
.then(compose(join(''), map(u => `<img width="" src="${u}"/>`)))
Now it looks like:
const {prop, filter, map, sortBy, propEq, join, compose, pluck} = R
const deckUrl = 'https://deckofcardsapi.com/api/deck/new/shuffle/?cards=AS,2S,5C,3C,KD,AH,QH,2C,KS,8C'
fetch(deckUrl)
.then(res => res.json())
.then(deck => fetch(`https://deckofcardsapi.com/api/deck/${deck.deck_id}/draw/?count=10`)
.then(res => res.json())
.then(prop('cards'))
.then(filter(propEq('suit', 'CLUBS')))
.then(map(prop('image')))
.then(sortBy(prop('value')))
.then(compose(join(''), map(u => `<img width="" src="${u}"/>`)))
.then(imgString => {
document.querySelector('#cards').innerHTML = `<div>${imgString}</div>`
})
We can also pull out each step as a function.
const {prop, filter, map, sortBy, propEq, join, compose, pluck} = R
const deckUrl = 'https://deckofcardsapi.com/api/deck/new/shuffle/?cards=AS,2S,5C,3C,KD,AH,QH,2C,KS,8C'
const getId = prop('deck_id');
const drawCards = id => fetch(`https://deckofcardsapi.com/api/deck/${id}/draw/?count=10`)
.then(res => res.json());
const getCards = prop('cards');
const justClubs = filter(propEq('suit', 'CLUBS'));
const sortByValue = sortBy(prop('value'));
const getImages = map(prop('image'));
const toImgString = compose(join(''), map(u => `<img width="" src="${u}"/>`));
const render = imgString => {
document.querySelector('#cards').innerHTML = `<div>${imgString}</div>`
};
fetch(deckUrl)
.then(res => res.json())
.then(getId)
.then(drawCards)
.then(getCards)
.then(justClubs)
.then(getImages)
.then(sortByValue)
.then(toImgString)
.then(render);
Using R.pluck to replace R.map(R.prop(''));
const getImages = pluck('image');
const {prop, filter, map, sortBy, propEq, join, compose, pluck} = R
const deckUrl = 'https://deckofcardsapi.com/api/deck/new/shuffle/?cards=AS,2S,5C,3C,KD,AH,QH,2C,KS,8C'
const getId = prop('deck_id');
const drawCards = id => fetch(`https://deckofcardsapi.com/api/deck/${id}/draw/?count=10`)
.then(res => res.json());
const getCards = prop('cards');
const justClubs = filter(propEq('suit', 'CLUBS'));
const sortByValue = sortBy(prop('value'));
const getImages = pluck('image');
const toImgString = compose(join(''), map(u => `<img width="" src="${u}"/>`));
const render = imgString => {
document.querySelector('#cards').innerHTML = `<div>${imgString}</div>`
};
const transformData = compose(toImgString, getImages, sortByValue, justClubs, getCards)
fetch(deckUrl)
.then(res => res.json())
.then(getId)
.then(drawCards)
.then(compose(render, transformData));
[Ramda] Refactor a Promise Chain to Function Composition using Ramda的更多相关文章
- [Ramda] Convert a QueryString to an Object using Function Composition in Ramda
In this lesson we'll use a handful of Ramda's utility functions to take a queryString full of name/v ...
- [Ramda] Refactor to a Point Free Function with Ramda's useWith Function
Naming things is hard and arguments in generic utility functions are no exception. Making functions ...
- [Typescript] Promise based delay function using async / await
Learn how to write a promise based delay function and then use it in async await to see how much it ...
- [Javascript] Understand Function Composition By Building Compose and ComposeAll Utility Functions
Function composition allows us to build up powerful functions from smaller, more focused functions. ...
- [Ramda] Convert a Promise.all Result to an Object with Ramda's zip and zipObj
In this lesson, we'll use Promise.all to get an array that contains the resolved values from multipl ...
- [Ramda] Refactor to Point Free Functions with Ramda using compose and converge
In this lesson we'll take some existing code and refactor it using some functions from the Ramda lib ...
- Function Composition vs Object Composition
In functional programming, we create large functions by composing small functions; in object-oriente ...
- [Ramda] Create a Query String from an Object using Ramda's toPairs function
In this lesson, we'll use Ramda's toPairs function, along with map, join, concatand compose to creat ...
- [Ramda] Filter an Array Based on Multiple Predicates with Ramda's allPass Function
In this lesson, we'll filter a list of objects based on multiple conditions and we'll use Ramda's al ...
随机推荐
- 洛谷 P1497 木牛流马
P1497 木牛流马 题目描述 孔明造出了木牛流马 木牛者,方腹曲头,一脚四足,头入领中,舌著于腹.载多而行少,宜可大用,不可小使:特行者数十里,群行者二十里也.曲者为牛头,双者为牛脚,横者为牛领,转 ...
- tomcat的classloader机制
本系列博客打算分析一下tomcat7.x的源码,其中可能会穿插一些java基础知识的介绍 读tomcat的源码的时候,我建议和官方的User Guide一起阅读,明白tomcat做某件事情的目的之后 ...
- [React Intl] Render Content with Placeholders using react-intl FormattedMessage
Learn how to use react-intl to set dynamic values into your language messages. We’ll also learn how ...
- @RequestMapping value 能够反复吗 [
@RequestMapping value 能够反复吗 [问题点数:40分,结帖人wangqiao4j] 不显示删除回复显示全部回复 显示星级回复显示得分回复 仅仅显示楼主 u=http://bbs. ...
- amazeui学习笔记--js插件(UI增强4)--下拉组件Dropdown
amazeui学习笔记--js插件(UI增强4)--下拉组件Dropdown 一.总结 1.am-dropdown(及其孩子):控制下拉列表的样式 2.data-am-dropdown(及其孩子):控 ...
- wepy小程序实现列表分页上拉加载(1)
使用wepy开发微信小程序商城第一篇:项目初始化 使用wepy开发微信小程序商城第二篇:路由配置和页面结构 列表页效果图: 1.新建列表页 (1)在pages里面新建一个list.wpy文件 初始代码 ...
- (转)Nginx在RedHat中系统服务配置脚本
转自:http://binyan17.iteye.com/blog/1688308 以下代码是在前人的基础上,结合自己服务器实际情况修改的,本人服务器环境是:CentOS 6.31.创建启动脚本, ...
- DBeaver无法执行数据库脚本
网上查了查相关问题,自己写了个步骤,记录下来方便以后查找 此处我连接的是mysql数据库,就以mysql为例说明: 在使用DBeaver过程中,别人给了几个sql文件,想直接导入数据库中,正常流程应该 ...
- SoC中的IP模块学习
SoC中的IP模块学习 理解IP Spec-->register定义,理解原理+架构框图 查看testcase+model(看已有的测试例程),分析操作/使用模块的流程,寄存器的配置方法 运行仿 ...
- [Angular 2] Set Values on Generated Angular 2 Templates with Template Context
Angular 2 templates have a special let syntax that allows you to define and pass a context when they ...