JavaScript: Function as arguments
Wanted to create a chain of method call backs with some simple JavaScript as in
startMethod -> calls function on success and another function on failure and it had been awhile since I did this refreshed my memory on Promises and Object.assign
First create a variable like so to hold both branches of execution like so
var actions = {
onSuccessFn: function() {
console.log("All good");
},
onFailureFn: function() {
console.log("No no no");
}
};
startMethod(actions);Define the start method to handle the override functions as args
function startMethod(overrideFns) {
// Assign defaults and fallback to null if none given
var currentCallbacks = Object.assign({
onSuccessFn: null,
onFailureFn: null
}, overrideFns || {});
...
// Promise currentPromise gets defined here
...
currentPromise.then(() => {
if ((currentCallbacks.onSuccessFn !== null) &&
(typeof currentCallbacks.onSuccessFn === "function")) {
currentCallbacks.onSuccessFn();
} else {
console.log("Default");
}
})
.catch(err => {
if ((currentCallbacks.onFailureFn !== null) &&
(typeof currentCallbacks.onFailureFn === "function")) {
currentCallbacks.onFailureFn();
} else {
console.log(err);
}
});
}This is close enough to what I wrote to trigger my memory, so need this to jog my memory on promises. Was debating on using the shortened method of == relying on JavaScript implicit conversion like so
currentCallbacks.onSuccessFn instanceof Function but I am not as comfortable with this and decided to stick with the more explicit null check and function type comparison