My node.js script reads rows from a table in database 1, does some processing and writes the rows to database 2.
The script should exit after everything is done.
How can I know if everything has been done and exit node then?
If I have a callback function like this:
function exit_node() {
process.exit();
}
(Edit: in the meantime it became obvious that process.exit() could be also replaced with db.close() - but this is not the question what to put in there. The question is at which time exactly to do this, i.e. how and where to execute this callback.)
But it is not easy to attach it somewhere. After the last read from db1 is not correct, because the processing and writing still has to happen.
Attaching it to the write to db2 is not easy, because it has to be attached after the last write, but each write is indepenent and does not know if it is the last write.
It could also theoretically happen, that the last write finished, but another write before that is still executing.
Edit: Sorry, I can see the explanation of the question is not complete and probably confusing, but some people still understood and there are good answers below. Please continue reading the comments and the answers and it should give you the whole picture.
Edit: I could think of some "blocking" controller mechanism. The different parts of the script add blockers to the controller for each open "job" and release them after the job is finished, and the controller exits the script when no more bockers are present. Maybe async could help: https://github.com/caolan/async
I also fear this would blow up the code and the logic unreasonable.