Skip to content

Instantly share code, notes, and snippets.

View nem035's full-sized avatar
🐢
always learning

Nemanja Stojanovic nem035

🐢
always learning
View GitHub Profile
httpGet(url, once(processValue));
function once(cb) {
var hasExecuted = false;
return function callbackWrapper() {
if (!hasExecuted) {
hasExecuted = true;
cb.apply(this, arguments);
}
}
httpGet(url1, function(res) {
// here we'll receive value1
});
httpGet(url2, function(res) {
// here we'll receive value2
});
function processValues(value) {
// we want to call this function first for value1,
// this doesn't work
try {
httpGet(function callback() {
// an error caused asynchronously
// cannot be caught via a callback
// mechanism
})
} catch (err) {
// this will only get called if httpGet
// itself throws a synchronous error
// when performing an async operation that requires a callback
// we have to immediately provide that callback
// and would need to maintain or pass around a reference to
// the callback in our codebase if we wanted to handle the
// response in a different place from where we started the async
// process.
httpGet(function callback() {
// we have to provide this callback immediately
// when starting this operation and cannot do
// it at a later point.
var globalState; // callbacks have to talk through global state
httpGet(function callback1(value) {
globalState.callback1 = value;
})
httpGet(function callback2(value) {
globalState.callback2 = value;
})
[1,2,3].forEach(function callback(num) {
// this code runs synchronously
})
// this line isn't reached until the
// array above is fully iterated on
function * fibonacciGen() {
let prev1 = 1;
let prev2 = 1;
while (true) {
let next = prev1 + prev2;
yield prev1;
prev1 = prev2;
prev2 = next;
}
}
var fn = co.wrap(function* (val) {
// we can yield a promise
// which behaves like await-ing it
return yield Promise.resolve(val);
});
fn(true).then(function (val) {
});
function computeMaxCallStackSize() {
try {
return 1 + computeMaxCallStackSize();
} catch (e) {
return 1;
}
}
function recurseForever() {
recurseForever();
}
recurseForever();
// outputs
// Uncaught RangeError: Maximum call stack size exceeded