[Compose] 19. Leapfrogging types with Traversable

We use the traversable instance on List to reimplement Promise.all() type functionality.

 

For example we want to conver:

[Task] => Task([])

Conver array of Task, into Task of array value.

 

To do that we can use traverse

Noraml Javascript array doesn't have traverse method, so we need to bring immutable-ext.

const fs = require('fs')
const Task = require('data.task')
const futurize = require('futurize').futurize(Task)
const { List } = require('immutable-ext')

const readFile = futurize(fs.readFile)

const files = List(['box.js', 'config.json'])

files.traverse(Task.of, fn => readFile(fn, 'utf-8'))
.fork(console.error, console.log)

 

Here 'futurize' give us a easy way to wrap a function into a Task. We can do it manually as well:

/*
const readFile = (filename, encode) => new Task((rej, res) => {
    return fs.readFile(filename, encode, (err, content) => {
        if (err) rej(err);
        res(content);
    });
});*/
const readFile = futurize(fs.readFile);

 

上一篇:数字图像处理--图像梯度算子的本质


下一篇:38.(c#)取远程用户IP地址