在nodejs中通过异步游标的简单方法

时间:2014-04-16 00:55:45

标签: node.js asynchronous cursor

我想编写最后一段可以通过异步游标的代码。 我从以下(破碎)代码开始:

function something( done ){

  stores.someStore.select( {}, { cursor: true }, function( err, cursor ){

    var processItem = function( err, item ){

      console.log("Item before check:", item );
      if( item === null ) return;

      console.log("Item:", item );
      cursor.next( processItem);
    };

    cursor.next( processItem );
  });
}

这显然非常破碎:

  • 不检查错误
  • 光标完成后,我无法在goThroughCursor内完成任务

我想出了这个看起来过于复杂的解决方案,必须是一个更好的方法...

function goThroughCursor( cursor, processItem, cb ){

  function f(){

    cursor.next( function( err, item ){

      if( err ) return cb( err );
      if( item === null ) return cb( null );

      processItem( item, function( err ){
        if( err ) return cb( err );

        f();
      });
    });
  }
  f();
};


function something( done ){

  stores.someStore.select( {}, { cursor: true }, function( err, cursor ){
    if( err ) return done( err );

    var processItem = function( item, cb ){
      console.log("Item is: ", item ); 
      cb( null );
    }

    goThroughCursor( cursor, processItem, function( err ){
      if( err ) return done( err );

      console.log("Cursor done!");
    });
  });
}

因此,basicaly goThroughCursor()是一个通用函数,它会将next()调用到游标,并在它返回null时停止。对于每个有效项目,它将运行processItem()

然后我只使用该函数,将cursorprocessItem()函数传递给它。

这样太复杂了吗?

使用异步,我会这样做(这仍然很冗长):

function something( done ){

  stores.someStore.select( {}, { cursor: true }, function( err, cursor ){
    if( err ) return done( err );

    var item;
    async.doWhilst(
      function( callback ){
        cursor.next( function( err, i ){
          if( err ) return callback( err );

          item = i;
          if( item !== null ){
            console.log( "ITEM IS:", item );
          }

          callback( null );
        });
      },

      function(){ return item != null; },

      function( err ) {
        if( err ) return done( err );

        console.log( "ALL DONE!" );
        done( null );
      }
    );

  })
}

然而,即使是异步解决方案也太长了。当然,这必须是开发人员的常见问题......我错过了什么?

0 个答案:

没有答案