javascript - (node:30437) UnhandledPromiseRejectionWarning: Error: Callback function is not available with promise clients - Sta

My codeconnection.promise().query(sql, crit, (error) => {if (error) throw error;console.log(chalk.cy

My code

          connection.promise().query(sql, crit, (error) => {
            if (error) throw error;
            console.log(chalk.cyan.bold(`====================================================================================`));
            console.log(chalk.greenBright(`Role successfully created!`));
            console.log(chalk.cyan.bold(`====================================================================================`));
            viewAllRoles();
          });

(node:30437) UnhandledPromiseRejectionWarning: Error: Callback function is not available with promise clients. at PromiseConnection.query (/Users/rachelmcgrath/Desktop/projects/employeeDatabase/node_modules/mysql2/promise.js:94:13) at viewAllEmployees (/Users/rachelmcgrath/Desktop/projects/employeeDatabase/server.js:122:24) at /Users/rachelmcgrath/Desktop/projects/employeeDatabase/server.js:51:9 at processTicksAndRejections (internal/process/task_queues.js:95:5) (Use node --trace-warnings ... to show where the warning was created) (node:30437) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see .html#cli_unhandled_rejections_mode). (rejection id: 1) (node:30437) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

My code

          connection.promise().query(sql, crit, (error) => {
            if (error) throw error;
            console.log(chalk.cyan.bold(`====================================================================================`));
            console.log(chalk.greenBright(`Role successfully created!`));
            console.log(chalk.cyan.bold(`====================================================================================`));
            viewAllRoles();
          });

(node:30437) UnhandledPromiseRejectionWarning: Error: Callback function is not available with promise clients. at PromiseConnection.query (/Users/rachelmcgrath/Desktop/projects/employeeDatabase/node_modules/mysql2/promise.js:94:13) at viewAllEmployees (/Users/rachelmcgrath/Desktop/projects/employeeDatabase/server.js:122:24) at /Users/rachelmcgrath/Desktop/projects/employeeDatabase/server.js:51:9 at processTicksAndRejections (internal/process/task_queues.js:95:5) (Use node --trace-warnings ... to show where the warning was created) (node:30437) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:30437) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Share Improve this question asked Jul 22, 2021 at 19:33 RachelRachel 1193 silver badges9 bronze badges 1
  • Looks like the documentation of the mysql2 package should hold the answer – Bergi Commented Jul 22, 2021 at 19:48
Add a ment  | 

3 Answers 3

Reset to default 3

When you select "View All Employees," this is the line that is running that is subsequently throwing an error message. In this case, this is because there are two ways that you can execute a query - either by using an inline callback, which is passed in as an argument, or by using a promise, which is returned by the query function call; however, they cannot both be used at the same time, which is what the snippet above is trying to do and is why an error is getting thrown. In other words, let's look at the two methods. First, we'll take a look at the inline callback. In this method, we use the connection variable (without .promise()) and then call query with two arguments: the first that is our SQL statement to execute, and the second is an anonymous function that has to parameters - one for if an error is thrown and the other for a successful response, as well as the data that was sent back from MySQL. The anonymous function will serve as our callback once MySQL data finished retrieving the data. This method can be written similar to the following:

Method 1: Query w/ inline callback

connection.query(sql, (error, response) => {
    if (error) throw error;
    console.log("Response: ", response);
});

Now, with that said, instead of using connection.query(), we can wrap connection.promise(), which will return a PromiseConnection class instance, and then we can use its query() method, which will then return a Promise. In this case, since we are using a Node promise, when we execute query(), there is only one argument that we need to supply: the SQL statement that we wish to run. From there, we can then use .then or .catch to either process a successful return or an error, respectively. This method can be written similar to the following:

Method 2: Query w/ promise-based callback

    .then(([ rows ]) => {
        console.log("Response: ", rows);
    })
    .catch(error => {
        throw error;
    });

The problem is that when using the promise.() method on your .query() you have to use a .then() after your sql query instead of a callback function. (A callback function being a function that is passed in as an argument to another function)

The way you have your code written right now includes a call back because of the function passed in as the third argument of the query

`

connection.promise().query(sql, crit, (error) => {
            if (error) throw error;
            console.log(chalk.cyan.bold(`====================================================================================`));
            console.log(chalk.greenBright(`Role successfully created!`));
            console.log(chalk.cyan.bold(`====================================================================================`));
            viewAllRoles();
          });

`

but can be switched to the following (or something like it) to avoid having the callback and thus be able to use .promise()

`

connection.promise().query(sql, crit)
        .then((data) => {
        //function goes in here
        }).catch(err)

`

To fire query we can do like this here with with pool, we can make promise where we get connection with db. Then we have other promise where we fire/execute query. Then release connection.

const pool = require('path to db confg file');
const fireQuery = async (req, res) => {

//make a connection with db it should be a callback function where await promise settles
const connection = await pool.getConnection();
try {
    // fire query
    const results = await connection.execute("sql query");
    res.status(200).json(results);
    } finally {
    connection.release();
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745125241a4612651.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信