为什么不在回调中工作函数?

Why don't work functions in callback?

本文关键字:函数 工作 回调 为什么不      更新时间:2023-09-26

第一个函数findOne工作正常。但是这里所有的Mongoose函数回调都不能正常工作,没有任何错误。为什么?谢谢你!

var mongoose = require('mongoose');
var Links = require('../models/Links');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/soft');
Links.findOne({}, function(err, l) {
  if (err) throw err;
  console.log("1", l);
  Links.findOne({}, function(err, l_) {
    if (err) throw err;
    console.log("2", l_);
  });
});
mongoose.connection.close();

代码在第二个.find有机会被调用之前关闭了连接。由于.find是异步的,代码执行第一个调用(它有一个连接来执行),但随后继续并在第一个调用返回执行第二个调用之前断开连接。

.close调用移到第二个调用中,将允许两个呼叫都进行。

var Links = require('../models/Links');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/soft');
Links.findOne({}, function(err, l) {
  if (err) throw err;
  console.log("1", l);
  Links.findOne({}, function(err, l_) {
    if (err) throw err;
    console.log("2", l_);
    mongoose.connection.close();
  });
});