Last active
August 31, 2016 01:32
-
-
Save RyanCCollins/9e64b4559109dfdae775daa411a23016 to your computer and use it in GitHub Desktop.
Forget Callback inversion of control, thunks are the way to go!
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
// Playing with Thunks | |
// See: http://jsbin.com/qebuluveje/edit?js,console | |
// Awesome! | |
const fakeAjax = (text, cb) => | |
setTimeout(() => { | |
cb(text); | |
}, 5000); | |
function getFile(file) { | |
var text, fn; | |
fakeAjax(file, (res) => { | |
if (fn) fn(res); | |
else text = res; | |
}); | |
return function(cb) { | |
if (text) cb(text); | |
else fn = cb; | |
} | |
} | |
let thunk1 = getFile("File 1: bacon bacon bacon"); | |
let thunk2 = getFile("File 2: brie brie brie"); | |
let thunk3 = getFile("File 3: async async async"); | |
const output = (text, index) => | |
console.log(`File #${index}. Contents: ${text}`); | |
thunk1((text1) => { | |
output(text1, 1); | |
thunk2((text2) => { | |
output(text2, 2) | |
thunk3((text3) => { | |
output(text3, 3) | |
console.log('Complete!') | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment