On Thu, Sep 12, 2013 at 12:44 PM, akira <[email protected]> wrote:

> All I want to do is create fixtures for my application doing:
>
> 1. Retrive an "profile" from a mongo db collection
> 2. Create a new empty object object and fill it with some data from the
> above profile
> 3. "export" the object, in this case a "Message"
>

As I said in my earlier message, module evaluation is always going to be
synchronous, and there's no way to make it block on completion of
asynchronous tasks. What you want to do is flip it around, and write your
setup as a function that gets passed the callback to be invoked once
Mongoose has your object:

var Profile = require('./../../models/profile');

module.exports = {
  name : 'Message',
  create : function (callback) {
    Profile.findOne({'username': 'test'}, function(err, profile) {
      if (err) return callback(err);

      callback(null, [{
        senderID: profile._id,
        receiverID: profile._id,
        text: "foobar1",
        seen: false,
        timeSent: {
          type: Date,
          default: Date.now
        },
        timeSeen: {
          type: Date,
          default: Date.now
        }
      }]);
    });
  }
};

Somewhere else you'd have some setup logic that looks like the following:

// elsewhere
function loaded() {
  console.log("all models loaded");
  // do whatever else here
}

var models = {};
var modelDefinitions = ['./app/models/message.js'];
toLoad = modelDefinitions.length;
modelDefinitions.forEach(function (path) {
  var model = require(path);
  model.create(function (err, template) {
    if (err) {
      console.error("unable to load template:", err.stack);
      process.exit(1);
    }
    else {
      models[model.name] = template; // or whatever comes out of
Mongoose factory method
    }

    // world's cheapest control flow
    toLoad--;
    if (toLoad < 1) loaded();
  });
});

Callback-driven asynchronous programming ends up requiring this kind of
inversion of control fairly frequently, which is why there are so many
discussions around control flow in the Node world. Take a look at using a
library like async, or maybe a promises library like Q, if you don't want
to deal with the control flow yourself.

F

-- 
-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to