Created
          July 12, 2016 04:22 
        
      - 
      
 - 
        
Save hoodwink73/e75e073d9267a0e6aa04d46a5e7d275d to your computer and use it in GitHub Desktop.  
    The thunk way to run parallel asynchronous operation but control the order of the callbacks
  
        
  
    
      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
    
  
  
    
  | function getFile (file) { | |
| var text, fn; | |
| fakeAjax(file, function oldSchoolCb (response) { | |
| if (fn) { | |
| fn(response) | |
| } else { | |
| text = response | |
| } | |
| }) | |
| return function thunk (cb) { | |
| if (text) { | |
| cb(text) | |
| } else { | |
| fn = cb | |
| } | |
| } | |
| } | 
  
    
      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
    
  
  
    
  | // just by declaring them, we are | |
| // making the requests, in parallel | |
| var file1 = getFile('file1'); | |
| var file2 = getFile('file2'); | |
| // although the request to both files | |
| // can resolve at whichever time they want | |
| // without any guarantee, | |
| // we will wait for the file1 to resolve | |
| // before file2 is resolved | |
| file1(function (text1) { | |
| console.log(text1); | |
| file2(function (text2) { | |
| console.log(text2) | |
| }) | |
| }) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment