无法弄清楚如何在node.js中使用synchronize.js

时间:2016-02-26 21:15:00

标签: javascript node.js asynchronous synchronize

我尝试在我的node.js应用中使用模块synchronize.js,但我失败了。功能仍然无序运行,我没有收到我的数据。 这是我的代码的一般摘要。

// 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 );
    });

但是会发生的事情是console.log显示函数没有等待:

yay we have a DB connector
[]
size: 0
Database 1 is connected ...
Database 2 is connected ...

有人能指出我做错了什么吗?如果需要,我可以更多地填写方法体,我只是试着保持简单。 我知道我的方法(函数)是正确的,因为如果我在setTimeout回调中包装底部console.log调用(光纤中的那些),那么我确实得到了我的数据。

2 个答案:

答案 0 :(得分:1)

我最终使用了async.js包。它更加用户友好"因为它有效!

修改 在async中,我这样做了:

// 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 );
});

答案 1 :(得分:0)

使用Node时,this is my favourite package代表承诺:

简单承诺:

return when.promise(function(resolveCallback, rejectCallback) {
        //do something here
    var blah = foo("bar");

    //return callback like this
    resolveCallback();
});

链式承诺:

返回when.promise(function(resolveCallback,rejectCallback){         //在这做点什么     var blah = foo(“bar”);

//return callback like this
resolveCallback();

})然后(X);

var x = function(){
     return when.promise(function(resolveCallback, rejectCallback) {
      //do something here
      var blah = foo("bar");

      //return callback like this
      resolveCallback();
        });
};