简单的方法来通过nodejs中的asynchronous光标

我想写最后一个可能的代码来通过一个asynchronous光标。 我从以下(破碎的)代码开始:

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做任何事情

我想出了这个解决scheme,看起来太复杂了, 必须有更好的方法来做到这一点…

 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!"); }); }); } 

所以,基本上, goThroughCursor()是一个generics函数,它将调用next()到一个游标,并在它返回为null时停止。 对于每个有效的项目,它将运行processItem()

然后,我简单地使用该函数,并将其传递给cursorprocessItem()函数。

这样太复杂了吗?

与asynchronous,我会这样做(这仍然相当详细):

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

但是,即使asynchronous解决scheme太长了。 当然,这对于开发者来说必须是一个常见的问题…我错过了什么?