I want to drop some mongodb collections, but that's an asynchronous task. The code will be:
var mongoose = require('mongoose'); mongoose.connect('mongo://localhost/xxx'); var conn = mongoose.connection; ['aaa','bbb','ccc'].forEach(function(name){ conn.collection(name).drop(function(err) { console.log('dropped'); }); }); console.log('all dropped');
The console displays:
all dropped dropped dropped dropped
What is the simplest way to make sure all dropped
will be printed after all collections has been dropped? Any 3rd-party can be used to simplify the code.
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
JavaScript provides three methods of handling asynchronous code: callbacks, which allow you to provide functions to call once the asynchronous method has finished running; promises, which allow you to chain methods together; and async/await keywords, which are just some syntactic sugar over promises.
The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console. log("Hello"); setTimeout(() => { console.
Use Promises.
var mongoose = require('mongoose'); mongoose.connect('your MongoDB connection string'); var conn = mongoose.connection; var promises = ['aaa', 'bbb', 'ccc'].map(function(name) { return new Promise(function(resolve, reject) { var collection = conn.collection(name); collection.drop(function(err) { if (err) { return reject(err); } console.log('dropped ' + name); resolve(); }); }); }); Promise.all(promises) .then(function() { console.log('all dropped)'); }) .catch(console.error);
This drops each collection, printing “dropped” after each one, and then prints “all dropped” when complete. If an error occurs, it is displayed to stderr
.
Use Q promises or Bluebird promises.
With Q:
var Q = require('q'); var mongoose = require('mongoose'); mongoose.connect('your MongoDB connection string'); var conn = mongoose.connection; var promises = ['aaa','bbb','ccc'].map(function(name){ var collection = conn.collection(name); return Q.ninvoke(collection, 'drop') .then(function() { console.log('dropped ' + name); }); }); Q.all(promises) .then(function() { console.log('all dropped'); }) .fail(console.error);
With Bluebird:
var Promise = require('bluebird'); var mongoose = Promise.promisifyAll(require('mongoose')); mongoose.connect('your MongoDB connection string'); var conn = mongoose.connection; var promises = ['aaa', 'bbb', 'ccc'].map(function(name) { return conn.collection(name).dropAsync().then(function() { console.log('dropped ' + name); }); }); Promise.all(promises) .then(function() { console.log('all dropped'); }) .error(console.error);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With