我想从 MySQL 表中获取变量,并根据变量值打开我的 Web 应用程序窗口。我在应用程序的服务器端编写了 MySQL 连接查询。因此,当服务器连接建立时,可能会发生上述流程。 但是在获取变量值之后,代码不会向前运行,并且在 Debug模式下光标最终会成为 y 的返回值。 请有人帮助解决这个问题。提前致谢。
#!/usr/bin/env node
'use strict';
require('dotenv').config({silent: true});
var server = require('./app');
var port = process.env.PORT || process.env.VCAP_APP_PORT || 8000;
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var def = function(){
server.listen(port, function() {
// eslint-disable-next-line
console.log('Server running on port: %d', port);
return;
});
}
var X;
global.x = X;
var mysql = require('mysql');
var mysqlPool = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'emp',
debug : true
});
var abc = function(){
mysqlPool.getConnection(function(err, connection) {
connection.query("select exp from empid where id= 12345", function(err, rows){
if(err) {
throw err;
} else {
var y = rows[0].exp;
}
//connection.release();
*return y;*
});
});
}
def();
abc();
if(abc > 2) {
window.location.href = "http://www.w3schools.com";
}
最佳答案
您无法从回调中返回值,因为您的 abc()
函数在 return
语句运行之前返回 - 请注意 return
> 从使用它的函数返回,而不是从某个外部函数返回。
如果您想在数据库查询处理程序之外使用该值,则可以返回 promise 或使用回调。
有关详细信息,请参阅这些答案:
- Return Promise result instead of Promise in Nodejs
- Return value in function from a promise block
- A detailed explanation on how to use callbacks and promises
- Explanation on how to use promises in complex request handlers
- An explanation of what a promise really is, on the example of AJAX requests
- An explanation of callbacks, promises and how to access data returned asynchronously
关于javascript - MySQL查询后无法运行js命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42112975/