Skip to content Skip to sidebar Skip to footer

Nodejs Asynchronous Programming - Coordinating Parallel Calls

I was referring this nodetuts tutorial on coordinating parallel calls in NodeJs. http://nodetuts.com/series/asynchronous-programming/mastering-asynchronous-programming-02.html The

Solution 1:

You can always use async parallel or stuff like that.

As for the manual implementation, you can do one of the following:

1- Long poll the amount of finished tasks. If # of finished tasks == total # of tasks => final callback

2- At the end of every individual callback, send an "I'm done" signal and check the amount of "I'm done" signals. If the amount of "I'm done" signals is equal to total number of tasks => final callback.

Looks like you're going with 2nd approach. Checking your code, I don't see you missing any aspect, but you have one big problem:

If your first task finishes before you register the second task, you execute the final callback only with the result of the first task.

To restate: The way you register your tasks brings up a race condition that highly depends on the fact that you roll high enough from random timeouts so that you can register all your tasks before the ones that you registered all finish.

Suggested fix: Don't start any of your tasks before you successfully register all of them.

Also: If you start your pending at 0 and execute order = pending, you get a pending = 2 when you register 3 tasks and none of them finish, and after the second task finishes and the 3rd task is still under way, you execute the final callback.

Post a Comment for "Nodejs Asynchronous Programming - Coordinating Parallel Calls"