Node.js-使用异步函数以同步方式获取返回值而无需回调

时间:2019-03-03 06:38:21

标签: mysql node.js asynchronous callback

我具有从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 } )
  )
}

经过数小时的关于Promise和回调的学习,我终于能够使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)

2 个答案:

答案 0 :(得分:1)

这是一个非常令人困惑的话题,花了我一段时间才真正理解为什么根本无法问自己(至少以你问的确切方式)。对于示例,我将使用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函数将其他函数(即回调)作为其参数,并在执行查询后执行该函数。如果要在不使用“回调”一词的情况下执行相同的操作,则可以使用fsociety之类的await / async函数,也可以显式地编写代码,而不要使以其他函数作为参数的函数。

此功能与上面的代码相同:

var connection = mysql.createConnection(config);
connection.query('SELECT * FROM USERS', function(error, users) { 
if (error) throw error;
console.log(users); 
});

回调地狱是不可避免的,但是一旦掌握了它确实还不错。

答案 1 :(得分:0)

改为使用异步等待功能。

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)
  }
}

希望这会有所帮助!