简体   繁体   English

在有条件防止此类情况发生时,两个console.log()如何执行?

[英]How come both console.log() execute when there is a condition to prevent such a thing from happening?

I am trying to automate the MySQL server startup once I start my application with the following code: 一旦我使用以下代码启动应用程序,便试图自动启动MySQL服务器:

 var exec = require('child_process').exec; let check = new Promise((resolve, reject) => exec('mysql-ctl status', function(error, stdout, stderr) { if (error) reject(error); else resolve(stderr); }) ); let start = new Promise((resolve, reject) => exec('mysql-ctl start', function(error, stdout, stderr) { if (error) reject(error); else resolve(console.log("MySQL server is up!")); }) ); async function check_status() { return await check; } async function start_server(status) { if (status.trim() == 'MySQL is stopped') { console.log("Starting MySQL server..."); await start; } else console.log("MySQL server was up..."); } module.exports = async function() { check_status() .then((status) => start_server(status)) .catch((error) => console.log("Error: " + error)); }; 

However, if the server is already up, I get the following output: 但是,如果服务器已经启动,则会得到以下输出:

 App Started. Listening on PORT 8080 MySQL server was up... MySQL server is up! 

How come both console.log() are executing when there is a condition to prevent precisely that? 有条件的情况下,两个console.log()如何执行?

When you are calling new Promise(resolve, reject => ()) you are starting execution of function given to promise. 当您调用new Promise(resolve, reject => ())您将开始执行赋予promise的功能。 That function is executed asynchronously. 该函数是异步执行的。

So in your case you start checking if MySQL is running and next you start script for starting MySQL, but before check is finished. 因此,在您的情况下,您将开始检查MySQL是否正在运行,然后在启动检查之前启动用于启动MySQL的脚本。

module.exports = async function() {
  check_status()
    .then((status) => start_server(status))
    .catch((error) => console.log("Error: " + error));
};

When this function is executed you are just awaiting result from check in check_status() . 当执行此功能你只是等待结果checkcheck_status() But that check was started when check variable is created. 但是,当创建check变量时,该检查已开始。

Result of this is in your then method => MySQL server is up! 结果是您的then方法=> MySQL server is up! . When check is being executed start is also being executed and because MySQL server is not started you are getting Starting MySQL server... 当执行check时,还将执行启动,并且由于未启动MySQL服务器,因此您正在Starting MySQL server...

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

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