3 ms·
If A, B, C, and D truly are asynchronous then I believe you're going to need condition variables and (at a lower level) locks. I agree that such syntax should
by Periodic 17y ago
If A, B, C, and D truly are asynchronous then I believe you're going to need condition variables and (at a lower level) locks. I agree that such syntax should be baked in and handled at a lower level.
If you can guarantee that a given variable can only be modified by one process at a time, it is easy to do something to take care of this for individual processes, and wouldn't be hard to generalize.
(note, I was last using prototype.js, and my javascript is a bit rusty)
wait_list = [];
function wait_for(entry) {
wait_list.push(entry);
};
function done(entry) {
wait_list.splice(wait_list.indexOf(entry), 1);
if (wait_list.length == 0) {
do_C();
}
};
function do_A () {
wait_for("A");
// do stuff
done("A");
};
function do_B () {
wait_for("B");
// do stuff
done("B");
};
function do_C () {
// Stuff that comes after A and B
};
- rictic 17y agoNope, no locks needed in Node. This is one of the little joys of javascript: no threading at all. None. With Web Workers you can have processes, but there isn't shared state; everything is done through message passing. All parallelism is cooperative in javascript, meaning that you don't have to worry about control flow switching out from under you at arbitrary points, just when you explicitly yield it by returning from an event handler or from the top level of your program. Finally, to answer the grandparent question, the easiest answer is a promise group. A promise group is basically a promise that emits a success event once all of its child promises have emitted success events. There are a few implementations floating around, though it's just a handful of lines of code to write and makes for a good exercise. So assuming that A and B are rewritten to return promises (or wrapped, I believe that isaacs has a library which will wrap functions which take a callback to return a promise instead), you can do the following: var promise_a = do_A(); promise_a.onSuccess(do_C); var promise_b = do_B(); promise_b.onSuccess(do_D); var promise_group = new PromiseGroup([promise_a, promise_b]); promise_group.onSuccess(do_E);
- scotty79 17y ago> Finally, to answer the grandparent question I don't event have a kid! ;-) Thank you, that was the thing I was looking for. My question now: What happens if one of the promises fails? Is a promise group disposed then? Solution offered by Periodic would wait forever.
- simonw 17y agoIt depends on the promise library implementation - most will let you specify an "errback" (like a callback, but called if there is an error) and will trigger that if any of their children fail. Alternatively, some may let you specify a timeout and call your errback if that time elapses without all of the children finishing.
- Periodic 17y agoLooks like the formal name for what I was trying to do. Now I know what to google!