mysql - 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
解决方案
您在评论中提到您希望等待查询块之后的逻辑,而不是将该逻辑放在回调中。通过使用 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
}
推荐阅读
- java - 如何从一个由多个动词和介词组成的复杂句子中获得主语、动词和宾语?
- python - while循环python可以只执行一次语句吗?
- php - FosElasticaBundle 填充序列化程序不索引所有字段
- python - 找不到满足要求 zipfile 的版本(来自版本:)
- r - 基于其他列表元素使用 lapply() 在列表数据框中添加新列
- node.js - 重定向到根 url,在节点 js 中传递一些响应数据
- ocaml - Ocaml,二叉树的级别函数
- html - 如何使 Angular 组件出现在 HTML 模板中?
- angular - Angular:如何将一个数组复制到另一个数组?
- python - 继承的 c 'abstract' 方法也要检查其他继承的类,而不仅仅是子类