I've been chipping away at learning Javascript via Eloquent Javascript. I am currently on Chapter 11: Asynchronous Programming.
Below I tried to make a callback-based version of a promise-based function given in an example included in the book.
Does this look equivalent to you guys? Testing suggests that it MIGHT be, but there is a rabbit hole of unpredictability introduced into other functions (to simulate network behaviour) that interact with this part of the code - so results are always slightly different. Any comments/suggestions would be appreciated.
All relevant code for this chapter is in these two files: crow-tech-js and 11_async.js as available in the online Code Sandbox for this chapter.
Promise-based anon function given in book:
(nest, content, source, callback) => {
try {
Promise.resolve(handler(nest, content, source)).then(response => callback(null, response), failure => callback(failure));
} catch (exception) {
callback(exception);
}
}
//Below is the closure for 'handler' above (don't know if that is how you use 'closure' in a sentence)
(nest, {name,neighbors}, source) => {
let connections = nest.state.connections;
if (JSON.stringify(connections.get(name)) == JSON.stringify(neighbors)) return;
connections.set(name, neighbors);
broadcastConnections(nest, name, source);
}
My equivalent callback-based anon function
(nest, { name, neighbors }, source, callback) => {
try {
let connections = nest.state.connections;
if (JSON.stringify(connections.get(name)) == JSON.stringify(neighbors)) {
callback(null);
return;
}
connections.set(name, neighbors);
broadcastConnections(nest, name, source);
callback(null, true);
}
catch (e) {
callback(e);
}
}