首页 > 解决方案 > MySQL NodeJS .then() 不是函数

问题描述

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

// 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

标签: mysqlnode.jspromise

解决方案


您在评论中提到您希望等待查询块之后的逻辑,而不是将该逻辑放在回调中。通过使用 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
}

推荐阅读