Skip to content

Instantly share code, notes, and snippets.

@loujaybee
Last active May 13, 2019 11:34
Show Gist options
  • Save loujaybee/dcf9aa0e5fceb6e537a27cf97de9fe61 to your computer and use it in GitHub Desktop.
Save loujaybee/dcf9aa0e5fceb6e537a27cf97de9fe61 to your computer and use it in GitHub Desktop.
Get out of the circular!
class Initialisation {
constructor() {
this.aFunctionThatThrowsImmediately();
this.aFunctionThatThrowsLater();
}
// Fake stuff to show the return values of module
aFunctionThatThrowsImmediately() {
console.log(this.errorCallback()); // error thrown, but platform not set
}
aFunctionThatThrowsLater() {
setTimeout(() => {
console.log(this.errorCallback()); // error found: platform-arbitrary-id
}, 1000);
}
async getPlatform () {
return "platform-arbitrary-id";
}
// Set a default no-op errorCallback (in case error is thrown)
errorCallback() {
return "error thrown, but platform not set"
}
// Expose a setter for platform
setErrorCallback(errorCallback) {
this.errorCallback = errorCallback;
}
}
class Error {
constructor(getPlatform) {
this.setPlatform(getPlatform);
}
async setPlatform(getPlatform) {
this.platform = await getPlatform();
}
onError() {
return `error found: ${this.platform}`;
}
}
const initInstance = new Initialisation();
const errorInstance = new Error(initInstance.getPlatform);
initInstance.setErrorCallback(errorInstance.onError.bind(errorInstance));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment