MySQL Node JS .then() 不是函数

标签 mysql node.js promise

我不能使用 promise 进行 nodeJS mysql 查询吗?

// My DB settings
const db = require('../util/database');

db.query(sqlQuery, [param1, param2])
        .then(result => {
            console.log(result);
        })
        .catch(err => {
            throw err;
        });

返回:TypeError: db.query(...).then is not a function

最佳答案

您在评论中提到您希望等待查询 block 之后的逻辑,而不将该逻辑放在回调中。通过使用 Promise 包装方法,您可以这样做:

try {
    const result = await new Promise((resolve, reject) => {
        db.query(sqlQuery, (error, results, fields) => {
            if (error) return reject(error);
            return resolve(results);
        });
    });

    //do stuff with result
} catch (err) {
    //query threw an error
}

关于MySQL Node JS .then() 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59290574/

相关文章:

php crumbtrail 使用文件名

node.js - Node : child_process. js:427 抛出新的 TypeError ("This handle type can' t 被发送");

node.js - 要使用新的解析器,请传递选项 { useNewUrlParser : true } to MongoClient. connect

javascript - 异步请求中的angularjs简单.then或$q服务

javascript - 在 promise 数组上使用 'all' 聚合函数时的最终处理程序

Typescript 柯里化(Currying)和异步函数

mysql - 在 vba 中从 QUery 填充数组,然后将数据插入表中

mysql - 如何在 MySQL 中返回数据透视表输出?

mysql - 另一个 mysql 服务器在 OS X 上已经运行错误

node.js - Sequelize 查询返回 Promise { _bitField : . ..}