简体   繁体   English

强制程序执行,直到功能完成

[英]Force program execution to wait until function finishes

I am trying to make a connection to a database and would like to see that my code stops executing while the connection has not been established yet. 我正在尝试建立与数据库的连接,并且希望看到在尚未建立连接的情况下我的代码停止执行。 So it can print an error/success message to the console at the right time (before the program will output that startup was successful). 因此,它可以在正确的时间将错误/成功消息打印到控制台(在程序将输出启动成功之前)。

My current code to establish the connection is: 我当前建立连接的代码是:

dbConnectAsync = async () => {
  try {
    await mongoose.connect("mongodb://localhost:27017/meetstation", { useNewUrlParser: true });
    console.log(SUCCESS_MSG);
  } catch (err) {
    console.log(ERROR_MSG);
    console.log(err.name);
  }
}

I know it is possible to put all other code inside the try block but this is not desirable as I plan on moving the function that establishes the database connection to an other file. 我知道可以将所有其他代码放在try块中,但这不是理想的,因为我计划将建立数据库连接的功能移至另一个文件。

Is there any way to call this function that forces other execution of code to wait until this function is done executing? 有什么方法可以调用该函数,以强制其他代码执行等待该函数执行完毕?

Within your code you can await dbConnectAsync and then run after the successful connection occurs. 在您的代码中,您可以等待dbConnectAsync ,然后在成功建立连接后运行。 So code will appear in a separate try/catch block, but not in the internal try/catch of dbConnectAsync . 因此,代码将出现在单独的try / catch块中,而不出现在dbConnectAsync的内部try / catch中。

async function program() {
    try {
        await dbConnectAsync();
        // code that executes after successful connection
    } catch (err) {
        // handle connection error
    }
}

One change I would mention is to use throw in the catch block of dbConnectAsync so that any consuming code can respond to it. 我要提到的一个更改是在dbConnectAsync的catch块中使用throw ,以便任何使用代码的都可以对其进行响应。 My example above won't receive any errors as a result. 我上面的示例不会因此收到任何错误。

You could extract the database setup function into module: 您可以将数据库设置功能提取到模块中:

// db.js
let connection;

export async function setup() {
  try {
    connection = await mongoose.connect('mongodb://localhost:27017/meetstation', { useNewUrlParser: true });
    console.log(SUCCESS_MSG);
  } catch (err) {
    console.log(ERROR_MSG);
    console.log(err.name);
  }
}

export function getConnection() {
  return connection;
}

Init the connection and then start your application: 初始化连接,然后启动您的应用程序:

// main.js
import { setup, getConnection } from './db.js';

(async function bootstrap() {
  await setup();

  // start your application
  // using getConnection()
})();

Actually your server can't do much without a database. 实际上,如果没有数据库,您的服务器将无法完成很多工作。 Therefore the most appropriate reaction in case of an error is just to crash. 因此,发生错误时最适当的反应就是崩溃。 With top-level await I would just write a module like this: 顶层等待的情况下,我只需要编写如下模块:

  export * from "mongoose";
  import { connect } from "mongoose";

  await connect("mongodb://localhost:27017/meetstation", { useNewUrlParser: true });

Then whenever you use mongoose, import it from that file and not from "mongoose" itself. 然后,每当您使用猫鼬时,请从该文件而不是从"mongoose"本身导入它。 That way, no code will run until the database is ready and in case of an error the server does crash. 这样,在数据库准备就绪之前,任何代码都不会运行,并且如果发生错误,服务器也将崩溃。

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

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