Last active
          March 17, 2017 01:09 
        
      - 
      
- 
        Save alexandrebodin/f6de17adb428a0149ca46ada925a4e47 to your computer and use it in GitHub Desktop. 
    pipe & branch async code
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import _ from 'lodash/fp'; | |
| const pipe = (...list) => | |
| (args) => | |
| _.flatten(list).reduce((p, fn) => p.then(fn), Promise.resolve(args)) | |
| const branch = (...list) => | |
| (args) => Promise.all(list.map(fn => fn(args))) | |
| function getUsersByIds([id1, id2]) { | |
| return [ | |
| { | |
| id: id1, | |
| }, | |
| { | |
| id: id2, | |
| } | |
| ]; | |
| } | |
| function getUsersFriends(arr) { | |
| return arr.map((val, index) => ({ | |
| name: 'friend-' + index, | |
| })); | |
| } | |
| function getUsersN1(arr) { | |
| return arr.map((val, index) => ({ | |
| name: 'N1-' + index, | |
| })); | |
| } | |
| function log(arr) { | |
| console.log(JSON.stringify(arr, null, 2)); | |
| } | |
| const identity = data => data; | |
| function getStuffByNames(names) { | |
| return names.map(name => 'Alex connait ' + name); | |
| } | |
| const selectArg = (argNb) => ([...args]) => args[argNb]; | |
| pipe( | |
| getUsersByIds, | |
| branch( | |
| user => user, | |
| pipe( | |
| getUsersFriends, | |
| friends => friends.map(f => f.name), | |
| getStuffByNames | |
| ), | |
| getUsersN1 | |
| ), | |
| ([user, friends, n1]) => ({ | |
| users: { | |
| user, | |
| n1, | |
| friends, | |
| } | |
| }), | |
| branch( | |
| identity, | |
| log | |
| ), | |
| selectArg(1) | |
| )([1,2]) | |
| .then(res => { | |
| console.log(res); | |
| }) | |
| .catch(err => { | |
| console.log(err); | |
| }) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment