[Compose] 18. Maintaining structure whilst asyncing

We take our Promise.all() analogy further by using traversable on a Map(). Then we use two traversals in the same workflow.

 

Traverse is good for maintaning the original data structure:

复制代码
const Task          = require('data.task');
const { List, Map } = require('immutable-ext');

const httpGet = (path, params) => Task.of(`${path} result`);


// map
const res0 = Map(
    {
        home  : '/',
        about : '/about'
    }
).map(route =>
        httpGet(route, {})
);
console.log(res0); // Map{ home: Task(), about: Task()}
复制代码

For example, the code here return Map({Task}) instead of Map({}). 

 

So we can actually replace map with traverse.

复制代码
// Traverse
Map(
    {
        home: '/',
        about: '/about'
    }
).traverse(
    Task.of,
    route => httpGet(route, {})
).fork(console.error, console.log); // Map { "home": "/ result", "about": "/about result" }
复制代码

Now we are able to keep the same structure as before.

 

We can also use double traverse if needed, for example we change data to array of path inside of string:

复制代码
// Double traverse
Map(
    {
        home: ['/', '/home'],
        about: ['/about', '/help']
    }
).traverse(
    Task.of,
    routes =>
        List(routes)
            .traverse(
                Task.of,
                route => httpGet(route, {})
            )
).fork(
    console.error, console.log
); // Map { "home": List [ "/ result", "/home result" ], "about": List [ "/about result", "/help result" ] }
复制代码

Because Array doesn't have traverse function, so we need to use List from immutable.

posted @   Zhentiw  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-12-22 [Polymer] Introduction
2015-12-22 [Redux] Implementing combineReducers() from Scratch
2015-12-22 [Redux] Reducer Composition with combineReducers()
2014-12-22 [Bower] Bower
点击右上角即可分享
微信分享提示