当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - async.eachSeries not working as expected

问题描述:

I'm having a hard time with async.eachSeries. I've created a peace of code to illustrate.

const arr = [1, 2, 3, 4, 5, 6, 7];

function doJob(callback){

debugger; //#1

async.eachSeries(arr, function(task, cb){

console.log('Starting checking function');

debugger; //#2

if(task%2 === 0){

debugger; //#3

console.log('Task even: ' + task);

r.exists("somekty", function(err ,result){

if(err || result){

debugger; //#4

cb(null);

}else{

debugger; //#5

cb(null);

}

});

}else{

debugger;//#6

console.log('Task odd: ' + task);

cb(null);

}

debugger;//#7

}, function(err){

callback()

});

}

setTimeout(function(){

doJob(function(){

console.log('All done!');

})

}, 1000)

When I execute the code above, the expected result shoud be(for me):

Hit: #1

1 iteration: #2 - #6

2 iteration: #2 - #3 - #7 - #4||#5

3 iteration: ....

...

And keep going.... but what happens is when it goes for the first time inside the "if" that has a async function(redis) it just goes to #7 and never stops at #4 or #5 and finishes the code. Why?

I'm using iron-node for debugging.

网友答案:

but what happens is when it goes for the first time inside the "if" that has a async function(redis) it just goes to #7 and never stops at #4 or #5 and finishes the code. Why?

That's how async code works. If r.exists() is async, then calling it STARTS the operation and then the rest of your code continues to execute. async operations do not block until complete. Calling them just starts the operation and then the rest of your code continues to execute.

So, when task%2 === 0, then you would go into that branch of your code. It would then call r.exists(...). That will initiate that async operation and then the lines of your code after that will continue to run.

The next thing that executes in your code is debugger;//#7 so that will trigger.

At that point async.eachSeries() will come into play and will not execute the next iteration of your loop until somebody calls cb(null), which in your code will happen when r.exists() finishes and calls its callback.

When task%2 === 0, you should see this sequence:

#2, #3, #7, #4|#5

which is apparently what you observe.


FYI, it can sometimes be confusing to understand the real timing of your code when using lots of debugger breakpoints because stopping at the breakpoint itself influences the timing of various operations (it gives native code async operations a chance to run and complete while sitting at the breakpoint). When understanding pure timing of asynchronous operations, it is usually better to just use console.log() statements to output enough info to document the real sequence of things.

分享给朋友:
您可能感兴趣的文章:
随机阅读: