0

No promises, no async etc I wondered if this pattern is acceptable - my function is called and i'm passed a callback. I need to do 2 things before I can call that back:

function doSomething(..args.., callbackThatNeeds1And2DoneFirst){

    var done1 = false;
    var res1 = someAsync1(function call1callback(){ 
      //blah
      done1 = true;

      maybeComplete();
    });

    var done2 = false;
    var res2 = someAsync2(function call2callback(){ 
      //blah
      done2 = true;

      maybeComplete();
    });

    function maybeComplete(){
      if(done1 && done2){
        callbackThatNeeds1And2DoneFirst();
      }
    }

}

I suppose the questions is about variable scope - can multiple "concurrent" executions interfere with each other's values for done1 and done2, or does each call get its own variable scope?

ottomeister
  • 5,415
  • 2
  • 23
  • 27
Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • Unless I'm missing something in this code, by the time you test for done1 and done2, you most certainly won't have any of those variables set, because of the async calls. – xlecoustillier Oct 18 '18 at 08:29
  • You're right, thanks! Edited.. – Caius Jard Oct 18 '18 at 08:31
  • This should work. But here you make the "local" callbacks aware of a more general concern (`maybeComplete`), that they shouldn't know about. This could be acceptable in some narrow cases, but this is not applicable application wide. What if a local callback function comes from elsewhere where maybeComplete is not accessible for instance ? – xlecoustillier Oct 18 '18 at 08:55
  • I was thinking that the maybeComplete would be scoped within the function being called (see further edit), but I don't do a lot of node/js so I'm not well up on the scope/distance to which youre referring – Caius Jard Oct 18 '18 at 09:28
  • 1
    this would probably work but you'd probably be better off making a simple queue that always has your callback as the final entry. each function would take in a `next` parameter which would get called at the end of its run. first populate your queue, then trigger the first function in it. – Derek Oct 18 '18 at 19:11
  • Notice there's no reason not to use promises even in old versions of node. – Bergi Oct 18 '18 at 19:13
  • @bergi Oh, I thought node had to have reached a certain version (5.6?) - this is node 0.9 (6 years ago?)! And I think I'd get my ass kicked for installing new modules.. – Caius Jard Oct 19 '18 at 04:24

1 Answers1

1

Yes, this pattern is fine. It does basically what Promise.all does today, except that it works for exactly two asynchronous callbacks only not a variable amount.

Can multiple "concurrent" executions interfere with each other's values for done1 and done2, or does each call get its own variable scope?

Every call to doSomething creates a new scope with new done1 and done2 variables.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375