[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 ...
随机推荐
- js遍历对象的属性和方法
js遍历对象的属性和方法 一.总结 二.实例 练习1:具有默认值的构造函数 实例描述: 有时候在创建对象时候,我们希望某些属性具有默认值 案例思路: 在构造函数中判断参数值是否为undefined,如 ...
- jquery中$(dom).each()和$(dom).length的使用
1.$(dom).each();在dom处理上用的比较多. $(selector).each(function(index,element){ //selector会遍历当前页面里所有匹配的jquer ...
- the steps that may be taken to solve a feature selection problem:特征选择的步骤
參考:JMLR的paper<an introduction to variable and feature selection> we summarize the steps that m ...
- 【原创】基于pyautogui进行自动化测试
前期准备: python3.6 pyautogui pywinauto 以下代码实现内容: 1.打开记事本 2.记事本中输入This is a test 3.保存内容 4.退出进程 import py ...
- js里的表格数组某个key去重
如Elemgnt的table绑定的数据要某个key是唯一的 var myarry = [ {name: 'liuyang',age :13}, {name:'jike',age:15}, {name: ...
- 手机用appnium,web自动化用eclips+webdriver2
手机用appnium,web自动化用eclips+webdriver2 吴建清 pycharm 1.安装环境2.pycharm类似eclipse,写脚本,运行脚本3.uiautomatorviewer ...
- Scala入门到精通——第十九节 隐式转换与隐式參数(二)
作者:摇摆少年梦 配套视频地址:http://www.xuetuwuyou.com/course/12 本节主要内容 隐式參数中的隐式转换 函数中隐式參数使用概要 隐式转换问题梳理 1. 隐式參数中的 ...
- MySQL—Install/Remove of the Service Denied
在Windos7下通过命令"mysqld --install"安装MySQL数据库时出现了"Install/Remove of the Service Denied&qu ...
- ocx中调用ocx
BOOL CXXXApp::InitInstance()中加入一句AfxEnableControlContainer();
- 【Codeforces Round #185 (Div. 2) A】 Whose sentence is it?
[链接] 链接 [题意] 告诉你每句话; 然后每句话是谁说的和开头与结尾的一段字符串有关. [题解] 一个一个判断就好; 注意大小<5的情况 [错的次数] 在这里输入错的次数 [反思] 在这里输 ...