循环访问数据而不等待异步的回调结果

时间:2014-10-09 23:25:15

标签: node.js asynchronous cursor

我需要编写代码:

  • 使用游标浏览数据
  • 每个项目都是要发送的电子邮件:它将运行sendMessage(),它将尝试发送电子邮件
  • 如果sendMessage()调用带有错误的回调,我想循环停止。
  • BUT!在sendMessage完成之前,我不希望循环停止。

这就是我所做的:

    var messageTo;
    async.doWhilst(

      function( callback ){
        var errInCycle = null;

        // This function will return the next object, OR
        // null if the cursor is finished.
        cursor.next( function( err, i ){
          if( err ) return callback( err );

          messageTo = i;

          // If messageTo is null, just return. This is here because
          // cursor.next WILL return 'null' to indicate the last one
          if( messageTo === null ) return callback( null );

          // ******************************************
          // THIS IS WHERE EACH MESSAGE IS EVALUATED
          // ******************************************                  

          // Get the config for that message from the application
          getTransportConfig( messageTo, function( err, transportConfg ){
            if( err ){
              errInCycle = err;
              return;
            } 
            // Send the message!
            // This will only ever return with err !== null when something goes horribly wrong.
            // Undeliverable messages and minor errors won't return err
            sendMessage( transportConfig.transport, stores, messageTo, transportConfig.config, function( err ){
              if( err ){
                errInCycle = err;
              }

            });
          });

          // This is in the right spot! This cycle doesn't wait for sendMessage() to finish.
          // Calls the callback. at this point, errInCycle might have been set by one
          // of the callbacks above -- in which case, the cycle will interrupt
          callback( errInCycle );

        });
      },

      // Cycle will continue as long as this is true at the end of each iteration
      function(){ return messageTo != null; },

      // This is execute by async at the end of the cycle, when the previous function returns false
      function( err ) {

        inCycle = false; 
        if( err ){
          logger.log( { error: err, system: true, logLevel: 3, message: "Error while cycling through messages to send. CRON interrupted!", data: { config: config, messageTo: messageTo } } );
        }
        debug( "CRON DONE!" );
        return; 
      }
    ); 

基本上,我是异步设置errInCycle;如果出现错误的错误,我希望循环停止 - 它将在下一次迭代时停止。

看起来很健康吗?有什么我想念的吗?我问,因为它不是我之前使用的模式,它似乎是我想要做的唯一真正的解决方案。

0 个答案:

没有答案