Idiomatic way to wait for multiple callbacks in Node.js

前端 未结 8 2220
旧巷少年郎
旧巷少年郎 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:15

    The simplest way increment an integer counter when you start an async operation and then, in the callback, decrement the counter. Depending on the complexity, the callback could check the counter for zero and then delete the file.

    A little more complex would be to maintain a list of objects, and each object would have any attributes that you need to identify the operation (it could even be the function call) as well as a status code. The callbacks would set the status code to completed.

    Then you would have a loop that waits (using process.nextTick) and checks to see if all tasks are completed. The advantage of this method over the counter, is that if it is possible for all outstanding tasks to complete, before all tasks are issued, the counter technique would cause you to delete the file prematurely.

提交回复
热议问题