node async waterfall using an array with callbacks that have arguments - javascript

I am getting an error that I do not understand. I am calling async.waterfall with an array of functions. The function is 'shortened' for clarity.
FabricCommand.prototype.do = function (callback, undoArray) {
var self = this;
if (undoArray === undefined) {
undoArray = [];
}
undoArray.push(self);
callback(null, undoArray);
};
I create the array as listed below: doCommands is an array and the objects are added as such:
doCommands.push(fabricCommand.do.bind(fabricCommand));
the waterfall setup:
async.waterfall(
doCommands,
function(err, undoCommands){
if (err) {
// do something ...
}
else {
console.log('we succeeded with all the do commands... and there are '
+ undoCommands.length
+ ' in the undoCommands but we will disregard it...');
}
}
);
Now when I run this code, the first time through the FabricCommand.do function, I allocate the undoCommands array and I add one to it, next time through I get, where I try to add the array element, the following error:
undoArray.push(something);
^ TypeError: Object function (err) {
if (err) {
callback.apply(null, arguments);
callback = function () {};
}
else {
var args = Array.prototype.slice.call(arguments, 1);
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
async.setImmediate(function () {
iterator.apply(null, args);
});
}
} has no method 'push'
Can anyone see what I am doing wrong?

The function that is executed by async.waterfall must have the following signature:
function(arg, callback) { … }
or, with multiple arguments:
function(arg1, arg2, callback) { … }
In your case, you simply inverted the two parameters:
FabricCommand.prototype.do = function (callback, undoArray) { … }
callback received the value intended to be stored in undoArray, and undoArray received the value intended for the callback, i.e. a function: that's why you encountered this weird error (function […] has no method 'push').
You need to put the parameters in the correct order:
FabricCommand.prototype.do = function (undoArray, callback) { … }
A second issue is that the first function of the waterfall receives only one parameter: the callback (because there is no value to be received, as it is the first function of the waterfall). A solution is to check the number of arguments:
if (Array.prototype.slice.apply(arguments).length === 1) {
callback = undoArray;
undoArray = undefined;
}
Here is a working gist.

Related

Passing parameters to a callback in javascript/nodejs

Hi I'm trying to understand callbacks in javascript and have come across this code here from a tutorial that I'm following:
var EventEmitter = require('events');
var util = require('util');
function Greetr() {
this.greeting = 'Hello world!';
}
util.inherits(Greetr, EventEmitter);
Greetr.prototype.greet = function(data) {
console.log(this.greeting + ': ' + data);
this.emit('greet', data);
}
var greeter1 = new Greetr();
greeter1.on('greet', function(data) {
console.log('Someone greeted!: ' + data);
});
greeter1.greet('Tony');
Now I notice that the greeter1.on function takes a callback with a parameter. However I'm not sure how this is implemented internally. I tried looking through the nodejs event.js file but I'm still confused. I am aware that there are ways around this specific implementation by using an anonymous function wrapping the callback with parameters but I want to understand how to use the same format as above.
tldr: How can I create my own function that takes a callback and a parameter in the same fashion as greeter1.on above.
Thank you
Your function needs to define a new property on the current instance with the callback passed as an argument, so it can be called later, like so:
function YourClass () {
this.on = function(key, callback) {
this[key] = callback;
}
}
// Usage
const instance = new YourClass();
instance.on('eventName', function (arg1, arg2) {
console.log(arg1, arg2);
});
instance.eventName("First argument", "and Second argument")
// logs => First argument and Second argument
Callback is just passing a function as a parameter to another function and that being triggered. You can implement callback fashion as below
function test(message, callback) {
console.log(message);
callback();
}
//Pass function as parameter to another function which will trigger it at the end
test("Hello world", function () {
console.log("Sucessfully triggered callback")
})
class MyOwnEventHandler {
constructor() {
this.events = {};
}
emit(evt, ...params) {
if (!this.events[evt]) {
return;
}
for (let i = 0, l = this.events[evt].length; i < l; i++) {
if (!params) {
this.events[evt][i]();
continue;
}
this.events[evt][i](...params);
}
}
on(evt, eventFunc) {
if (!this.events[evt]) {
this.events[evt] = [];
}
this.events[evt].push(eventFunc);
}
}
var myHandler = new MyOwnEventHandler();
myHandler.on('test', function (...params) {
console.log(...params);
});
myHandler.emit('test', 'Hello', 'World');

How to use common try-catch for processing every given function in Javascript?

These are some of my functions, I need to write a common function to see if functions are running without error. I tried with try/catch method. But I could only do that individually on each function.
function fisrt(){
console.log("First");
};
function second(){
console.log("Second");
}
function third(){
console.log("Third");
}
fisrt();
second();
third();
I was writing each function inside the try-catch. Is there a way I can write a common try-catch for all the functions.
try {
(function first() {
console.log("ffgdf")
})();
}catch (e) {
console.log( "won't work" );
}
You could define a wrapper function, that takes your desired function as a parameter, and wraps it in a try catch.
function wrapper(fn) {
try {
fn();
} catch(error) {
console.error(error);
}
}
Then given your original functions:
function first() {
console.log("First");
};
function second() {
console.log("Second");
}
function third() {
console.log("Third");
}
You can test each one by using your wrapper function:
wrapper(first);
wrapper(second);
wrapper(third);
Without needing to add try catch to each function.
Regarding the introducing sentence of the accepted answer two years ago ...
You could define a wrapper function, that takes your desired function as a parameter, and wraps it in a try catch.
... this part could be covered with (an) abstraction(s) where one also can provide the (different) handling of an invocation failure (the catch and exception clause).
If one does, for instance, provide functionality that wraps a function/method in way that does not only provide the try catch but also takes the exception handling into account, one can easily accomplish tasks, like the one asked by the OP for, which are mainly about programmable approaches for automatically creating and processing lists of functions/methods that are going to be invoked whilst suppressing unintended/unexpected invocation failures.
The following example does implement afterThrowing and afterFinally, two method modifier methods, each processing the original function/method with an exception handler as its first argument.
Making use of the provided abstraction(s) the approach itself boils down to writing reduce functionality which processes an array of functions by invoking each function with its own set of arguments and collecting its invocation success state ...
function first(...args) {
console.log("first :: does succeed :: argsList :", args);
return args.join(', ');
}
function second(...args) {
console.log("second :: going to fail :: argsList :", args);
throw new Error('2nd invocation failed.');
}
function third(...args) {
console.log("third :: going to fail :: argsList :", args);
throw new Error('3rd invocation failed.');
}
function fourth(...args) {
console.log("fourth :: does succeed :: argsList :", args);
return args.join(', ');
}
function fifth(...args) {
console.log("fifth :: does succeed :: argsList :", args);
return args.join(', ');
}
/**
* reduce functionality which processes an array of functions.
*/
function collectResultAfterThrowing(collector, fct, idx) {
function afterThrowingHandler(error, argsArray) {
// - can access the try-catch exception and the arguments
// that have been passed prior to the invocation failure.
return {
success: false,
failure: {
message: error.toString(),
argsList: Array.from(argsArray)
}
}
}
function unifyResult(value) {
return ((
value
&& value.hasOwnProperty('success')
&& (value.success === false)
&& value
) || { success: true, value });
}
collector.results.push(
unifyResult(fct // - modify original function towards an
.afterThrowing(afterThrowingHandler) // `afterThrowing` handling of its try-catch result(s).
.apply(null, collector.listOfArguments[idx])
)
// - an `afterThrowing` modified function does always return either the result of the
// original function's invocation or the return value of its 'afterThrowing' handler.
);
return collector;
}
/**
* reduce functionality which processes an array of functions.
*/
function collectResultAfterFinally(collector, fct, idx) {
function isError(type) {
return (/^\[object\s+Error\]$/).test(Object.prototype.toString.call(type));
}
function createResult(value) {
return (isError(value) && {
success: false,
message: value.toString()
} || {
success: true,
value
});
}
collector.results.push(
createResult(fct // - modify original function towards an
.afterFinally(() => null) // `afterFinally` handling of its try-catch result(s).
.apply(null, collector.listOfArguments[idx])
)
// - an `afterFinally` modified function does always return either the result of the
// original function's invocation or the try-catch exception of the invocation attempt.
);
return collector;
}
// ... two times, each the actual task,
// ... once based on "afterThrowing" and
// ... once based on "afterFinally" ...
console.log('"afterThrowing" based try-and-catch results :', [
first,
second,
third,
fourth,
fifth
].reduce(collectResultAfterThrowing, {
listOfArguments: [
['foo', 'bar'],
['baz', 'biz'],
['buz', 'foo'],
['bar', 'baz'],
['biz', 'buz']
],
results: []
}).results
);
console.log('\n\n\n');
console.log('"afterFinally" based try-and-catch results :', [
first,
second,
third,
fourth,
fifth
].reduce(collectResultAfterFinally, {
listOfArguments: [
['foo', 'bar'],
['baz', 'biz'],
['buz', 'foo'],
['bar', 'baz'],
['biz', 'buz']
],
results: []
}).results
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
(function (Function) {
const fctPrototype = Function.prototype;
const FUNCTION_TYPE = (typeof Function);
function isFunction(type) {
return (
(typeof type == FUNCTION_TYPE)
&& (typeof type.call == FUNCTION_TYPE)
&& (typeof type.apply == FUNCTION_TYPE)
);
}
function getSanitizedTarget(target) {
return ((target != null) && target) || null;
}
function afterThrowing/*Modifier*/(handler, target) {
target = getSanitizedTarget(target);
const proceed = this;
return (
isFunction(handler) &&
isFunction(proceed) &&
function () {
const context = target || getSanitizedTarget(this);
const args = arguments;
let result;
try {
result = proceed.apply(context, args);
} catch (exception) {
result = handler.call(context, exception, args);
}
return result;
}
) || proceed;
}
// afterThrowing.toString = () => 'afterThrowing() { [native code] }';
function afterFinally/*Modifier*/(handler, target) {
target = getSanitizedTarget(target);
const proceed = this;
return (
isFunction(handler) &&
isFunction(proceed) &&
function () {
const context = target || getSanitizedTarget(this);
const args = arguments;
let result, error;
try {
result = proceed.apply(context, args);
} catch (exception) {
error = exception;
} // finally { ... }
result = (error || result);
handler.call(context, result, args);
return result;
}
) || proceed;
}
// afterFinally.toString = () => 'afterFinally() { [native code] }';
Object.defineProperty(fctPrototype, 'afterThrowing', {
configurable: true,
writable: true,
value: afterThrowing/*Modifier*/
});
Object.defineProperty(fctPrototype, 'afterFinally', {
configurable: true,
writable: true,
value: afterFinally/*Modifier*/
});
}(Function));
</script>
In case of you wishing to get a "throwed" exception, you can use the Promise.all.
function parent() {
function first() {
console.log('First');
throw new Error('First error');
}
function second() {
console.log('Second');
}
function third() {
console.log('Third');
}
return Promise.all([
first(),
second(),
third(),
])
}
parent()
.then(result => console.log(result))
.catch(error => console.error(error))

Anonymous function argument

I have a section in my code that looks like this
var locationDefer = $.Deferred();
if (saSel.Company === -1) {
database.getAllLocations().then(function (result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
});
} else {
database.getLocationsForCompany(saSel.Company).then(function (result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
});
}
However, since it is basically the same thing twice, just with a different ajax call - is there any way to either have the anonymous function part
function (result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
})
declared as a real function and then just called in the .then() clause, or can I somehow provide the to-be-called-function of the database object?
For the latter, I had something in my mind that could look like this, but I have no clue how to do the last line.
if(saSel.Company === -1) {
fun = 'getAllLocations';
arg = null;
} else {
fun = 'getLocationsForCompany';
arg = saSel.Company;
}
// database.fun(arg).then(function (result) {...});
You can define a function and pass its reference as success callback handler
//Define the function handler
function resultHandler(result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
}
if (saSel.Company === -1) {
fun = 'getAllLocations';
arg = null;
} else {
fun = 'getLocationsForCompany';
arg = saSel.Company;
}
//Invoke the method using Bracket notation
//And, pass the success handler as reference
database[fun](arg).then(resultHandler);
Additionally, as getLocationsForCompany() and getAllLocations() returns a promise, you shouldn't use $.Deferred() directly return Promise
return database[fun](arg);

How to add extra parameters to a function callback

I am using a few callbacks in an app that I'm writing. I am using Mongoose models and need to save a few different places. The save function takes a callback, and the callback gets error and model for its parameters, but I'd like to send the callback an extra parameter that the function needs. I'm not sure of the proper syntax to be able to do this. Below is some example code of what I'm going for...
var saveCallBack = function(err, model, email_address){
if(err) {
//handle error
}
else {
//use the third parameter, email_address, to do something useful
}
};
Below, token is a mongoose model. As I said, save takes a callback and gets passed error and model, but I'd like to also send my callback a variable email_address that I figure out at some other point. Obviously the appendParameter function is pseudo-code, but this is the type of functionality that I need.
token.save(saveCallBack.appendParameter(email_address));
If you make that the first parameter instead, you can use .bind().
token.save(saveCallBack.bind(null, email_address));
var saveCallBack = function(email_address, err, model){};
I'm using bind function for appending additional parameters for callbackes
var customBind = function (fn, scope, args, appendArgs) {
if (arguments.length === 2) {
return function () {
return fn.apply(scope, arguments);
};
}
var method = fn,
slice = Array.prototype.slice;
return function () {
var callArgs = args || arguments;
if (appendArgs === true) {
callArgs = slice.call(arguments, 0);
callArgs = callArgs.concat(args);
} else if (typeof appendArgs == 'number') {
callArgs = slice.call(arguments, 0);
}
return method.apply(scope || window, callArgs);
};
}
This customBind function accepts four arguments, first one is original callback function, second is the scope, third is additional parameters (array), and fourth is flag append or replace. If you set last parameter to false than only parameters in array will be available in this function.
and with this function you can simple add new parameters or to override the existing one
var callback = customBind(saveCallBack, this, [array_of_additional_params], true)
in this way all original parameters remain and your parameter will be appended to the end.
No matter how many parameter you defined, the callee will always pass the same parameter inside its process.
but it will be more simple, just use a variable that is visible from outside of the callback.
Eg:
var email = 'yourmail#mail.com';
var saveCallBack = function(err, model){
if(err) {
//handle error
}
else {
alert(email);
}
};
Updated (#Jason): then you can use Immediately-Invoked Function Expression (IIFE)
(function(mail){
var saveCallBack = function(err, model){
if(err) {
//handle error
}
else {
alert(mail);
}
};
token.save(saveCallBack);
}, emailAddress);

Mongoose passing class functions

When I pass functions to mongoose, it seems it no longer has a reference to this. Is there a better way to go about this? All functions are simplified for length reasons. I cannot edit the function getUsernameForId to take additional parameters.
I have class:
var class = new function() {
this.func1 = function(data) {
return data + "test";
}
this.func2 = function(data) {
var next = function(username) {
return this.func1(username); // THIS THROWS undefined is not a function
}
mongoose.getUsernameForId(1, func3);
}
}
mongoose is another class like this:
var getUsernameForId = function(id, callback) {
user_model.findOne({"id": id}, function(err, user) {
if(err) {
throw err;
}
callback(user.username);
});
}
How do I resolve the undefined is not a function error. I do not want to duplicate code because func1 is pretty long in reality.
It's not clear from your code how next is used, but if you need it to be invoked with correct this you can try to use Function.prototype.bind method:
this.func2 = function(data) {
var next = function(username) {
return this.func1(username);
}.bind(this);
mongoose.getUsernameForId(1, func3);
}
I assume that you simplified code for the post and next does more things in reality. But if it indeed just returns result of this.func1 then you could shorten it:
var next = this.func1.bind(this);

Categories