Node.js - Using await new Promise in mysql pool connection - SyntaxError: Unexpected token new

Node.js - Using await new Promise in mysql pool connection - SyntaxError: Unexpected token new

Node.js - 在 mysql 池连接中使用 await new Promise - SyntaxError: Unexpected token new

我正在尝试在池连接中使用新的承诺...但我收到此语法错误:新的意外令牌。我错过了什么?

错误:

let rowsPromise01 = await new Promise((resolve,reject)=>{
                              ^^^
SyntaxError: Unexpected token new

js:

const pool = require('./config/dbpool');    

pool.getConnection(function(err, connection) {
  if (err) throw err;

   let rowsPromise01 = await new Promise((resolve,reject)=>{
    connection.query("SELECT * FROM table01", function(err, rows) {
        //connection.release();
        if (err) {
          console.log(err);
          reject(err);
        } else {
          console.log('Found records: '+rows.length);
          resolve(rows);       
        }
    });
   });

   let rowsPromise02 = await new Promise((resolve,reject)=>{
    connection.query(SELECT * FROM table02,function(err, results) {
      connection.release();
      if (err) {
        console.log(err);
        reject(err);
      } else {
      console.log('Found records: '+result.length);
      resolve(results);
      }
    });

    });

});

dbpool.js 看起来像这样:

const mysql= require('mysql');

//database connection
var pool = mysql.createPool({
  connectionLimit: 10,
  host     : 'localhost',
  user     : 'root',
  password : 'password',
  database : 'database'
});

module.exports = {
  getConnection (callback) {
    pool.getConnection((err, conn) => {
      if(err) {
        return callback(err);
      }
      callback(err, conn);
    });
  },
  query (query, params=[], cb) {
    this.getConnection((err, conn) => {
        conn.release();
        if(err) return cb(err, null);
        conn.query(query, params, (err, res) => {
            if(err) return cb(err, null);
            return cb(null, res);
        });
    });
  }
}

这个错误有点转移注意力,问题实际上出在 await 关键字上,它只在标有 async 的函数内部有效,在你的情况下它丢失了.

修复:

pool.getConnection(async function(err, connection) { .... });

更多信息在这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Description