猫鼬的非同步系列

时间:2018-09-10 06:10:54

标签: javascript mongodb asynchronous mongoose

var mongoose = require('mongoose');
var mongoDB = "mongodb://jananton:password1@ds020168.mlab.com:20168/test_database";
var User = require('./models/User.js');
var async = require('async');

function establishConnection() {
  mongoose.connect(mongoDB, {
    useNewUrlParser: true
  }).then(
    () => {
      console.log("Connection successful")
    },
    (err) => {
      console.log("Warning!" + err)
    }
  );
  mongoose.Promise = global.Promise;
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'MongoDB connection error:'));
}

let users = [];

function createUser(user_name, user_status, user_position) {
  var newUser = new User({
    Name: user_name,
    _id: new mongoose.Types.ObjectId(),
    Status: user_status,
    Position: user_position
  });
  newUser.save((err) => {
    if (err) {
      console.log(err);
    }
  });
  console.log(newUser.Name);
  users.push(newUser);
};

//Call both functions, starting with establishConnection
async.series([
    establishConnection,
    createUser("Andy", "Administrator", "Whatever"),
  ],
  function(err, res) {
    mongoose.connection.close();
  })

在上面的代码中,我只是通过EstablishmentConnection()方法连接到了在mLab上托管的MongoDB数据库。第二个函数createUser创建一个文档并将其保存到数据库中。然后,使用

的控制台输出从async.series()函数内部调用这两个函数。
Andy
Connection successful

我不明白为什么首先输出 Andy 的信息,然后才记录 Connection成功的信息,因为prepareConnection()在createUser()之前。此外,猫鼬不会关闭连接(请参见async.series函数的回调函数)。有人可以解释一下为什么吗?

1 个答案:

答案 0 :(得分:0)

因此,您需要更正async.series的用法。 async.series要求每个函数在执行完成后都调用回调函数,因此该序列可以正常工作。

async.series([
    function(callback) {
        // do some stuff ...
        callback(null, 'one');
    },
    function(callback) {
        // do some more stuff ...
        callback(null, 'two');
    }
],
// optional callback
function(err, results) {
    // results is now equal to ['one', 'two']
});

因此,在您的情况下,您需要这样做,

var mongoose = require('mongoose');
var mongoDB = 
 "mongodb://jananton:password1@ds020168.mlab.com:20168/test_database";
var User = require('./models/User.js');
var async = require('async');

function establishConnection(callback) {
  mongoose.connect(mongoDB, {
    useNewUrlParser: true
  }).then(
    () => {
      console.log("Connection successful")
      callback(null, "Connection successful");
    },
    (err) => {
      console.log("Warning!" + err)
      callback(err);
    }
  );
  mongoose.Promise = global.Promise;
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'MongoDB connection error:'));
}

let users = [];

function createUser(user_name, user_status, user_position, callback) {
  var newUser = new User({
    Name: user_name,
    _id: new mongoose.Types.ObjectId(),
    Status: user_status,
    Position: user_position
  });
  newUser.save((err) => {
    if (err) {
      console.log(err);
      return callback(err);
    }
  });
  console.log(newUser.Name);
  users.push(newUser);
  return callback(null, newUser);
};

//Call both functions, starting with establishConnection
async.series([
    establishConnection,
    createUser("Andy", "Administrator", "Whatever", callback),
  ],
  function(err, res) {
    mongoose.connection.close();
  })

希望这对您有所帮助。