Idiomatic way to wait for multiple callbacks in Node.js

前端 未结 8 2156
旧巷少年郎
旧巷少年郎 2020-11-28 04:12

Suppose you need to do some operations that depend on some temp file. Since we\'re talking about Node here, those operations are obviously asynchronous. What is the idiomati

相关标签:
8条回答
  • 2020-11-28 04:35

    With pure Promises it could be a bit more messy, but if you use Deferred Promises then it's not so bad:

    Install:

    npm install --save @bitbar/deferred-promise
    

    Modify your code:

    const DeferredPromise = require('@bitbar/deferred-promise');
    
    const promises = [
      new DeferredPromise(),
      new DeferredPromise()
    ];
    
    do_something(tmp_file_name, (err) => {
      if (err) {
        promises[0].reject(err);
      } else {
        promises[0].resolve();
      }
    });
    
    do_something_other(tmp_file_name, (err) => {
      if (err) {
        promises[1].reject(err);
      } else {
        promises[1].resolve();
      }
    });
    
    Promise.all(promises).then( () => {
      fs.unlink(tmp_file_name);
    });
    
    
    0 讨论(0)
  • 2020-11-28 04:39

    There is no "native" solution, but there are a million flow control libraries for node. You might like Step:

    Step(
      function(){
          do_something(tmp_file_name, this.parallel());
          do_something_else(tmp_file_name, this.parallel());
      },
      function(err) {
        if (err) throw err;
        fs.unlink(tmp_file_name);
      }
    )
    

    Or, as Michael suggested, counters could be a simpler solution. Take a look at this semaphore mock-up. You'd use it like this:

    do_something1(file, queue('myqueue'));
    do_something2(file, queue('myqueue'));
    
    queue.done('myqueue', function(){
      fs.unlink(file);
    });
    
    0 讨论(0)
提交回复
热议问题