简体   繁体   English

猫鼬的异步系列

[英]async.series with 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();
  })

In the code above, I just connect to a my MongoDB database hosted on mLab via the establishConnection() method. 在上面的代码中,我只是通过EstablishmentConnection()方法连接到在mLab上托管的MongoDB数据库。 The second function, createUser, creates an document and saves it to the database. 第二个函数createUser创建一个文档并将其保存到数据库中。 Both functions are then calles from inside the async.series() function with the console output of 然后从async.series()函数内部调用这两个函数,控制台输出为

Andy
Connection successful

I dont`t understand why Andy is output first, only then Connection successful is logged, since establishConnection() comes before createUser(). 我不明白为什么首先输出Andy ,然后才记录连接成功 ,因为buildConnection之前位于createUser()之前。 Additionally, mongoose won't close the connection (see the callback function of the async.series function). 此外,猫鼬不会关闭连接(请参见async.series函数的回调函数)。 Can someone explain me why? 有人可以解释我为什么吗?

So you need to correct the usage of async.series. 因此,您需要更正async.series的用法。 async.series requires each function to call the callback function when its execution is completed, hence the series works properly. 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']
});

so in your case you need to do it like this, 因此,在您的情况下,您需要这样做,

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();
  })

Hope this might help you. 希望这对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM