HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Creating an async consumable object in Node

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
creatingnodeasyncobjectconsumable

Problem

Background

I have a situation where I have fixed number of objects with their own routines that would need to be called with the same initial message.

To accomplish this, I have a Factory that binds objects to a Composite object whose main method is to call methods on its subordinates without having to know how many it has.

This routine is to be called upon receiving a message from a queue, the client to that queue is responsible for initiating that procedure.

Code/ Question

Just to keep the code looking succinct, here are the individual modules for completeness.

//-------------------------------------------------------------------
// module1/index.js
//-------------------------------------------------------------------

function A () {}

A.prototype.method = function(msg, cb) {
  console.log('A class: %j', msg );
  cb(null, 'done message');
};

//-------------------------------------------------------------------
// module2/index.js
//-------------------------------------------------------------------

function B () {}

B.prototype.method = function(msg, cb) {
  console.log('B scraper: %j', msg);
  cb(null, 'done message');
};


Here is the factory that has the job of knowing what it imports and attaching the objects defined above to the Factory's caller:

//-------------------------------------------------------------------
// - factory.js
//-------------------------------------------------------------------

var A = require('./module1');
var B = require('./module2');

function Factory () {
  var o = Object.create(null);
  o.obj1 = new A();
  o.object2 = new B();
  return o;
}


Now here's the part that is in question. The method method does some 'clever' stuff to make something that the async library can understand and use. This code runs, and it about as efficient as it needs to be but I would like to ask if there is another, more readable way to build an object for use in async.parallel().

```
//--------------------------------------

Solution

There is an error that needs to be handled correctly:

self.objects[name].method(msg, function(err, results){

        if (err) { 
           return callback(err); 
        }
        return callback(null, results);

      });


You need to return the callback on the error, otherwise if an error comes down, you will hit both callbacks.

Code Snippets

self.objects[name].method(msg, function(err, results){

        if (err) { 
           return callback(err); 
        }
        return callback(null, results);

      });

Context

StackExchange Code Review Q#82380, answer score: 2

Revisions (0)

No revisions yet.