Skip to content

Instantly share code, notes, and snippets.

@boeserwolf
Created April 12, 2017 09:22
Show Gist options
  • Save boeserwolf/5b8a04113647201a30b223e8fd8bf956 to your computer and use it in GitHub Desktop.
Save boeserwolf/5b8a04113647201a30b223e8fd8bf956 to your computer and use it in GitHub Desktop.
Demonstration of how to RELEASE ZALGO
/**
* Demonstration of how to RELEASE ZALGO
* @author Bastian Masanek (2017)
*/
let cache;
function releaseZalgo(cb) {
if (cache) {
// This is synchronous and execucted immediately.
// YOU JUST RELEASED ZALGO!
return cb(cache);
// Correct approach:
// return process.nextTick(() => cb(cache));
}
// Any async operation here.
setTimeout(() => {
cache = 'All fine.';
cb(cache);
}, 1000);
}
function zalgoFactory() {
let listeners = [];
releaseZalgo(data => {
listeners.forEach(listener => listener(data));
});
return {
onData: listener => listeners.push(listener)
};
}
let a = zalgoFactory();
a.onData(data => {
console.log('data from a:', data);
let b = zalgoFactory();
// This will never be called because releaseZalgo() already executed
// BEFORE .onData() was even defined.
b.onData(data => {
console.log('data from b:', data);
});
let c = zalgoFactory();
// This will never be called because releaseZalgo() already executed
// BEFORE .onData() was even defined.
c.onData(data => {
console.log('data from c:', data);
});
});
/*
Example output:
$ node zalgo.js
data from a: All fine
Nothing else will happen after the first asynchronous call.
===============================================================================
RULE OF THUMB:
-------------------------------------------------------------------------------
Use Promises. You can't release Zalgo when using Promises:
function releaseZalgo() {
if (cache) {
return Promise.resolve(cache);
}
return new Promise((resolve, reject) => {
...
});
}
If you have (or want) to use callbacks, choose whether your function is
synchronous or asynchronous -- and stick with it.
Never mix those concepts, because it can lead to unpredictable, weird and
thus hard to track down errors in your application.
If you find Zalgo, you can fight it using process.nextTick().
References:
- Designing APIs for Asynchrony
http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony
- Don't release Zalgo!
https://github.com/oren/oren.github.io/blob/master/posts/zalgo.md
===============================================================================
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment