Reputation: 6300
Using loopbackjs
.
Somwhere in my code, I need to validate properties in a very custom way, so I can't use available validators.
Thus, I was thinking of using it like this:
var somevar = "someval";
var anothervar = "anothervar";
MyModel.createme = function(prop1, prop2, prop3, prop4, callback) {
async.parallel([
verify_prop1,
verify_prop2,
verify_prop3,
verify_prop4
], function(err, results) {
});
}
then I was going to create the functions for async:
//local methods
var verify_prop1 = function(callback) {
};
Here is where I realized I was stuck. If I write the functions inline inside the async.parallel call, I have access to the function parameters prop1, etc. But how do I get them into my verify_propX functions? Is the async pararell's function signature fixed? Am I overly complicating things?
In another file I am using three parallel functions in async and they got pretty big so it doesn't look nice and editing is becoming expensive.
So I'd like a clean async method separation...how can I do that?
Upvotes: 1
Views: 66
Reputation: 707258
Assuming the four verify functions can be the same function with just a different parameter passed to them, then you can DRY this up a lot by automatically creating an array of props from the arguments and then using async.map()
to iterate that array in parallel:
var somevar = "someval";
var anothervar = "anothervar";
MyModel.createme = function(prop1, prop2, prop3, prop4, callback) {
async.map([].slice.call(arguments, 0, 4), function(item, done) {
// insert code here to verify the prop passed here as item
// call done(null, result) when the proccesing is done
done(null, result);
}, function(err, results) {
// array of data here in results
});
}
Since you aren't really specifying what exactly needs to be passed to your worker functions and your comments say that some functions need more than one prop argument, you can use a mixture of inline and external functions calls. This lets you put the meat of the functionality in external functions, but you can do the setup locally in an inline function where you have access to all the arguments:
var somevar = "someval";
var anothervar = "anothervar";
MyModel.createme = function (prop1, prop2, prop3, prop4, callback) {
async.parallel([
function (done) {
verifyA(prop1, prop2, done);
},
function (done) {
verifyB(prop3, done);
},
function (done) {
verifyC(prop2, prop4, done);
}
], function (err, results) {
// everything done here
});
}
Done this way, you can structure your parallel operations any way you want, passing any number of arguments to each one.
Upvotes: 2
Reputation: 1591
async.parallel([
async.apply(verify_prop1, prop1),
async.apply(verify_prop2, prop2),
async.apply(verify_prop3, prop3),
async.apply(verify_prop4, prop4)
], function(err, results) {
Upvotes: 3