I'm trying to use the module synchronize.js in my node.js app, but I am failing. Functions are still running out of order, and I'm not getting my data. Here is a general snippet of my code.
// an object with devices to migrate
var devices2Migrate =
{
device_array: [],
init: function ( done )
{
sync.fiber(function()
{
//do init stuff
console.log( 'yay we have a DB connector' );
DB1.connect(function(err)
{
console.log( 'Database 1 is connected ...' );
}
DB2.connect(function(err)
{
console.log( 'Database 2 is connected ...' );
}
}, done);
},
loadDevices2Migrate: function ( done )
{
var self = this;
sync.fiber(function()
{
//get stuff from DB using query()
}, done);
}
}; //end of object
// load up all the data for the devices using the old style tables
sync.fiber(function(){
sync.await( devices2Migrate.init( sync.defer() ));
sync.await( devices2Migrate.loadDevices2Migrate( sync.defer() ) );
console.log( devices2Migrate.device_array );
console.log( "size: " + devices2Migrate.device_array.length );
});
But what happens is that the console.log shows that the functions are not waiting:
yay we have a DB connector
[]
size: 0
Database 1 is connected ...
Database 2 is connected ...
Can anyone point me to what I'm doing wrong? I can fill in the method bodies more if needed, I was just trying to keep it simple at first. I know my methods( functions ) are correct, because if I wrap the bottom console.log calls (the ones in the fiber) in a setTimeout callback, then I do get my data.
I ended up using the async.js package. It was more "user friendly" in that it worked!
EDIT: in async, I did this:
// load up all the data for the devices using the old style tables
async.series(
devices2Migrate.init( callback ),
devices2Migrate.loadDevices2Migrate( callback )
){
// land here when done
console.log( devices2Migrate.device_array );
console.log( "size: " + devices2Migrate.device_array.length );
});