Skip to content

Instantly share code, notes, and snippets.

@hoodwink73
Created July 12, 2016 04:22
Show Gist options
  • Save hoodwink73/e75e073d9267a0e6aa04d46a5e7d275d to your computer and use it in GitHub Desktop.
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
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
}
}
}
// 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