Last active
          November 17, 2015 01:05 
        
      - 
      
- 
        Save bangedorrunt/f1e93a023b96e57c95bc to your computer and use it in GitHub Desktop. 
    First step of understanding ES6 promise-aware generator
  
        
  
    
      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
    
  
  
    
  | // Provided that `request()` is a promise | |
| function *something() { | |
| var text1 = yield request('url1') | |
| var text2 = yield request('url2') | |
| var text3 = yield request('url3') | |
| } | |
| var it = something() // Start the something() generator | |
| var p1 = it.next().value // Code run to `var text1 = yield` and pause | |
| // Yield out the promise `request('url1')` | |
| // Handle the promise in the next line | |
| p1.then(val => it.next(val).value) // Code run to `var text2 = yield` and pause | |
| // Send back `val` to last yield `var text1 = val` | |
| // Return another promise `request('url2')` | |
| .then(val => it.next(val).value) // Code run to `var text3 = yield` and pause | |
| // Send back `val` to last yield `var text2 = val` | |
| // Return another promise `request('url3')` | |
| .then(val => it.next(val).value) // Code run to completion | |
| // Send back `val` to last yield `var text3 = val` | |
| // Doing things like above is not DRY | |
| // That is the idea of utility generator runner such as ES7 `asyn/await` pattern that automate this manual task | |
| async function something() { | |
| var text1 = await request('url1') | |
| var text2 = await request('url2') | |
| var text3 = await request('url3') | |
| } | |
| something() // That's it, no more Promise's manual handling | |
| // See how async code looks like sync code? That's thanks to generator power | |
| // Right now `something()` generator, only handle promise synchronously as following: | |
| // `text1` -> `text2` -> `text3` | |
| // Let's say, if we want `text3` has dependencies os result of `text1 and `text2` | |
| // and because `text1` and `text2` are async operation. We want them to execute | |
| // asynchronously then merge the results to `text3` as following | |
| // `text1` --async--`text2` -> `text3` | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment