rabashani
rabashani

Reputation: 1483

Promise inside a Promise

I am trying to create a utility service that will help other developers in my team, to execute specific queries, but without the hassle of opening and closing connections.

This is what i wrote:

module.exports.connect = function(runner){
  var connection; 
  return MongoClient.connect(url)
  .then( conn => {
    connection = conn;
    var db = connection.db('looladb');
    return db;
  })
  .then (db => runner(db))
  .then (() => connection.close())
  .catch(err => console.log('Error with mongo query', err));
}

and this is the usage pattern:

mongoClient.connect(db => {
		db
			.collection("users")
			.find({email: "[email protected]"})
			.toArray()
			.then(out => console.log('db result', out))
	})

This is nice, but I want the usage pattern to be like this -

mongoClient.connect()
  .then(db => {
    db
      .collection("users")
      .find({email: "[email protected]"})
      .toArray()
      .then(out => console.log('db result', out))
  })

Upvotes: 1

Views: 95

Answers (1)

James
James

Reputation: 82096

Sounds like a good candidate for the use of finally.

module.exports.connect = async () => {
  const connection = await MongoClient.connect(url);
  return new Promise(res => res(connection.db('looladb')))
    .catch(err => console.log('Error with mongo query', err))
    .finally(connection.close)
}

Note - as pointed out, finally isn't officially supported yet on Node but can be enabled via the --harmony-promise-finally flag. Alternatively, there are other packages you can use for support e.g. promise.prototype.finally or Bluebird

Upvotes: 3

Related Questions