Idiomatic way to wait for multiple callbacks in Node.js

前端 未结 8 2221
旧巷少年郎
旧巷少年郎 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: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);
    });
    

提交回复
热议问题