zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    马尔科夫过程的CKS方程的推导
    科研的一些工具和想法
    读研究生后的一些想法
    读过的一些好书以后可做参考
    latex学习笔记
    机器人工程师学习要求
    《MySQL实战45讲》(8-15)笔记
    《MySQL实战45讲》(1-7)笔记
    java11运行javaFX项目
    ClickHouse入门笔记
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6212763.html
Copyright © 2011-2022 走看看