Promises distribution of intermediate objects (NodeJS + MongoDB)

I am trying to use MongoDB with Promises in Node 4.x

In this example, I want:

  • Connect to my mongodb
  • THEN delete everything with the given key
  • THEN insert one entry
  • Then close the connection

fortunately, the mongodb client spits out Promises when you don't give it a callback. Here is what I came up with.

const MongoClient = require('mongodb').MongoClient;
const test = require('assert');

function insertDoc(doc, collName) {
  return MongoClient.connect('mongodb://localhost:27017/myDB')
    .then(db => {
      const col = db.collection(collName);
      return col.deleteMany({ 'Key': doc.key })
        .then(() => col.insertOne(doc))
        .then(result => test.equal(1, result.insertedCount))
        .then(() => db.close);
    });
}

The code seems to work, but the nested .then()"feels" wrong. Any ideas how to do this so that the object dbcan be used when I'm ready for .close()it?

+4
source share
3 answers

, promises , , . , .

.

function insertDoc(doc, collName) {
  const db = MongoClient.connect('mongodb://localhost:27017/myDB');
  const col = db.then(db => db.collection(collName));

  return col.deleteMany({ 'Key': doc.key })
    .then(() => col.insertOne(doc))
    .then(result => test.equal(1, result.insertedCount))
    // You've still got the 'db' promise here, so you can get its value
    // to close it.
    .then(() => db.then(db => db.close()));
}
+2

:

let db;

function insertDoc(doc, collName) {
  return MongoClient.connect(dsn)
    .then(connectedDb => {
      db = connectedDb;
      return col.deleteMany(doc)
    }) // now you can chain `.then` and still use `db`
}

, db , . , - , async/await. , babel - , .

async function insertDoc(doc, collName) {
  const db = await MongoClient.connect(dsn);
  const col = db.collection(collName);
  await col.deleteMany({Key: doc.key});
  const result = await col.insertOne(doc);
  await test.equal(1, result.insertedCount) // is this asynchronous?
  return db.close();
}

co/yield, , .

+1

, , . ( .then) ( , !)

, . , col. , :

var insertDoc = (doc, collName) => MongoClient.connect('mongodb://localhost:x/DB')
  .then(db => db.collection(collName).deleteMany({ 'Key': doc.key })
    .then(() => db.collection(collName).insertOne(doc))
    .then(result => test.equal(1, result.insertedCount))
    .then(() => db.close))
  .then(() => doSomethingElse());

) db.close). , , .:)

col . , , , db. , .

In real life, code does not always creep neatly, but I like the template where it does it when possible.

0
source

Source: https://habr.com/ru/post/1649331/


All Articles