我有一个函数从mysql数据库中检索UserID的列表。
function GetUsers(callback) {
UpdateLogFile('Function Call: GetUsers()')
var users = []
Database.execute( connectionStr,
database => database.query('select UserID from Users')
.then( rows => {
for (let i = 0; i < rows.length; i++){
users.push(rows[i].UserID)
}
return callback(users)
})
).catch( err => {
console.log(err)
})
}
以供参考:
数据库类来自here
const mysql = require( 'mysql' )
class Database {
constructor( config ) {
this.connection = mysql.createConnection( config )
}
query( sql, args ) {
return new Promise( ( resolve, reject ) => {
this.connection.query( sql, args, ( err, rows ) => {
if ( err )
return reject( err )
resolve( rows )
})
})
}
close() {
return new Promise( ( resolve, reject ) => {
this.connection.end( err => {
if ( err )
return reject( err )
resolve()
})
})
}
}
Database.execute = function( config, callback ) {
const database = new Database( config )
return callback( database ).then(
result => database.close().then( () => result ),
err => database.close().then( () => { throw err } )
)
}
经过几个小时的了解承诺和回调,我终于能够让GetUsers()
至少工作并返回我正在寻找的东西。但是,我似乎只能这样使用它:
GetUsers(function(result){
// Do something with result
})
但我真的希望能够在函数中使用传统的return语句,以便我可以像这样使用它:var users = GetUsers()
。我看过帖子说由于异步函数的性质,这是不可能的,但我仍然充满希望,因为我真的希望能够避免使用callback hell。我尝试了下面的代码,但“用户”在执行后只是未定义的结果。因此,我的主要目标是能够从GetUsers()
获得返回值而不将回调链接在一起,因为我有其他类似行为的函数。这可能吗?
var users
GetUsers(function(result){
users = result
})
console.log(users)
请改用async-await函数。
async function GetUsers(callback) {
try {
UpdateLogFile('Function Call: GetUsers()')
var users = []
let rows = await Database.execute( connectionStr,
database => database.query('select UserID from Users')
for (let i = 0; i < rows.length; i++){
users.push(rows[i].UserID)
}
return callback(users)
} catch(err) {
console.log(err)
}
}
希望这可以帮助!
这是一个非常令人困惑的话题,我花了一段时间才真正理解为什么你所要求的是不可能的(至少,你要问的确切方式)。对于示例,我将使用python Django和Node.js进行比较。
def synchronous():
print('foo') //this will always print first
print('bar')
def getUsers():
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM USERS') //this query is executed
users = cursor.fetchall()
print('foo') //this doesn't trigger until your server gets a response from the db, and users is defined
print(users)
function asynchronous() {
console.log('foo'); //this will also always print first
console.log('bar');
}
function getUsers() {
var connection = mysql.createConnection(config);
connection.query('SELECT * FROM USERS', function(error, users) { //this is a "callback"
console.log(users); //this will print
//everything inside of here will be postponed until your server gets a response from the db
});
console.log('foo') //this will print before the console.log above
console.log(users); //this will print undefined
//this is executed before the query results are in and will be undefined since the "users" object doesn't exist yet.
}
回调只是一旦得到响应就应该运行服务器的函数。我们通常使用实际的单词“callback”,如下所示:
function getUsers(callback) {
var connection = mysql.createConnection(config);
connection.query('SELECT * FROM USERS', function(error, users) {
if (error) throw error; //always do your error handling on the same page as your query. Its much cleaner that way
callback(users) //server asks what to do with the "users" object you requested
});
}
现在在服务器上的其他位置:
getUsers(function(users) {// the callback gets called here
console.log(users); //do what you want with users here
});
getUsers
函数将一些其他函数(即回调)作为其参数,并在执行查询后执行该函数。如果你想在不使用单词“callback”的情况下做同样的事情,你可以使用像fsociety这样的await / async函数,或者你明确写出你的代码而不是创建以其他函数作为参数的函数。
这个功能与上面的代码相同:
var connection = mysql.createConnection(config);
connection.query('SELECT * FROM USERS', function(error, users) {
if (error) throw error;
console.log(users);
});
回调地狱是不可避免的,但是一旦你掌握了它,它真的不是太糟糕了。