javascript - 为什么我的回调无法正常工作?

标签 javascript node.js

此方法运行在 Node 服务器

const express = require("express");
const app = express();

const fs = require("fs");
const connectDb = require("./config/db");

const __init__ = (local = false) => {
  fs.writeFile(
    "./config/default.json",
    `{
        "mongoURI": ${
          local
            ? `"mongodb://127.0.0.1:27017/test"`
            : `"mongodb+srv://admin:<password>@abc-xxghh.mongodb.net/test?retryWrites=true&w=majority"`
        }
      }`,

    function(err) {
      if (err) {
        return console.log(err);
      }

      connectDb();
    }
  );
};

__init__(true);

问题是,如果最初 mongoURI: 127.0.0.1:27017,如果我执行 __init__(false),Node 将尝试连接到 127.0 .0.1:27017,当它应该连接到 +srv uri 时。

如果我再次运行 __init__(false),它将连接到适当的链接。

同样,如果我随后运行 __init__(true),它会在应该连接到本地时连接到 srv+,如果我运行 __init__( true) 再次,只有这样它才会连接到本地。

我在这里做错了什么?我正在按预期使用回调,不是吗?


编辑:

//config/db
// for mongoDB connection
const mongoose = require("mongoose");
// require the directory
const config = require("config");
// get all contents of JSON file
const db = config.get("mongoURI");

const connectDb = async () => {
  try {
    console.log("connecting to mongodb", db);
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true
    });

    console.log("Mongo DB connected");
  } catch (err) {
    console.log("unable to connect to mongodb");
    console.log(err.message);
    //exit if failure
    process.exit(1);
  }
};

module.exports = connectDb;

我什至尝试过以下操作:

.....
  console.log("Developing locally:", local);

  // require the directory
  const config = require("config");
  // get all contents of JSON file
  const db = config.get("mongoURI");
  connectDb(db);
.....

但它仍然读取旧值

最佳答案

问题出在执行顺序上,因为 require 是同步的

现在的顺序是:

  1. const connectDb = require("./config/db");
  2. const config = require("config");
  3. const db = config.get("mongoURI");//这有旧值
  4. fs.writeFile(...
  5. await mongoose.connect(db, {//这是在使用 OLD REFERENCE

因此您需要像这样更改您的connectDb 函数:

const connectDb = async () => {
  const config = require("config");
  // get all contents of JSON file
  const db = config.get("mongoURI");

  try {
    console.log("connecting to mongodb", db);
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true
    });

    console.log("Mongo DB connected");
  } catch (err) {
    console.log("unable to connect to mongodb");
    console.log(err.message);
    //exit if failure
    process.exit(1);
  }
};

无论如何,我认为这不是一个更好的基于环境加载配置的方式,所以我建议使用工厂模式改进它。

关于javascript - 为什么我的回调无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58216133/

相关文章:

javascript - 将数组中的对象传递到查询者列表选项中

javascript - 选择小费时如何更新总金额

javascript - nodeJS Winston 模块示例未记录到控制台

node.js - Mongo 遭受大量故障

javascript - 如何用正则表达式获取最后一段?

javascript - 允许用户在页面中输入 JavaScript 并与其他用户共享?

javascript - 在异步存储中保存和删除每周计划 react native

node.js - Mashape Imgur node.js 图片上传

javascript - 在 url 中使用文章标题,而不是 id

node.js - 如何跟踪和处理 Node 中的事件