I use Node.js to write system scripts that run on the server. Due to the asynchronous nature of Node, my script exits before the database calls have a chance to complete and nothing is ever written to the database.
I use Mongoose as ORM and talk to MongoDB if that matters. Node.js offers calls to the SYNCHRONOUS method precisely for this reason, for example: https://nodejs.org/api/child_process.html
I think my questions are:
1) Does the mongoose provide a way to block, so my script might wait for the database call to return?
2) If not, is there another method that I should consider, and not something like:
(function wait () {
if (!SOME_EXIT_CONDITION) setTimeout(wait, 1000);
})();
3) Is Node not the best scripting tool? I love Node for developing web applications and can write nested callbacks or work with promises all day. But what about the scripting language?
EDIT ---------------------------------------------- -
The following is a brief example script for clarity:
var schema = mongoose.Schema({
});
var model = new (mongoose.model('ModelObject'))();
model['attribute'] = 42;
console.log('This gets printed first');
model.save(function(err) {
console.log('Nothing in the callback gets printed because callback is never called');
if(err) {
console.log('This never gets printed to the screen');
console.log('And consequently nothing is ever saved to mongo');
} else {
console.log('This never gets printed either');
}
});
console.log('This gets printed second');
source
share