NodeJs Asynchronous Programming - Coordinating Parallel Calls
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"