异步任务的实现过于复杂,我们使用folktale中的Task来演示
folktale 一个标准的函数式编程库
和lodash、ramda不同的是,他没有提供很多功能函数
只提供了一些函数式处理的操作,例如:compose、curry等,一些函子 Task、Either、MayBe等
了解folktale
const { compose, curry } = require('folktale/core/lambda')
let f = curry(2, (x, y) => {
return x + y
})
console.log(f(4, 5))
console.log(f(1)(2))
const { toUpper, first } = require('lodash/fp')
let fc = compose(toUpper, first)
console.log(fc(['one', 'two']))
Task函子
const { task } = require('folktale/concurrency/task')
const fs = require('fs')
const { split, find } = require('lodash/fp')
function readFile(filename) {
return task(resolver => {
// 错误优先
fs.readFile(filename, 'utf-8', (err, data) => {
if (err) resolver.reject(err)
resolver.resolve(data)
})
})
}
readFile('package.json')
.map(split('\n'))
.map(find(x => x.includes('version')))
.run()
.listen({
onRejected: err => {
console.log(err)
},
onResolved: value => {
console.log(value)
}
})
网友评论