我需要编写代码:
这就是我所做的:
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
;如果出现错误的错误,我希望循环停止 - 它将在下一次迭代时停止。
看起来很健康吗?有什么我想念的吗?我问,因为它不是我之前使用的模式,它似乎是我想要做的唯一真正的解决方案。