javascript - 从另一个类中的函数获取返回值
问题描述
如何获取另一个类中函数的返回值:
我有一个带有一些 SQLite 请求的类,我正在从另一个类中调用这个类,如下所示:
import lotManager from '../components/LotManager';
class LotView extends React.Component {
async loadLot(id) {
await console.log('retvalue', lotManager.testIt(id));
}
render() {
this.loadLot(12);
return (
// some code
);
}
}
还有我的 SQL 类:
const db = SQLite.openDatabase("db.db");
class LotManager extends Component {
getLotById = (id) => {
db.transaction(tx => {
tx.executeSql("SELECT * FROM LOTS WHERE ID = ?", [id],
function (tx, results) {
// results is the value i actually want to get
return results;
},
function (tx, error) { console.log("Error SELECT : ", error.message) }
);
});
}
}
const lotManager = new LotManager();
export default lotManager;
我的问题 :
将我的 SQLite 请求函数结果发送给我的班级的最佳方法是什么?现在我可以与函数交互,但无法获得返回值(我理解为什么这段代码不起作用,它只是为了解释我想要的)。
谢谢你的帮助!
解决方案
将 a 包裹Promise
在您的db.transaction
函数周围并返回承诺。每当内部回调完成时解决或拒绝。
class LotManager extends Component {
getLotById = (id) => new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql("SELECT * FROM LOTS WHERE ID = ?", [id],
function(tx, results) {
resolve(results);
},
function(tx, error) {
reject("Error SELECT : ", error.message);
}
);
});
});
}
现在您可以使用 athen
和catch
语法获取值。
const lotManager = new LotManager();
lotManager.getLotById(420)
.then(results => console.log(results))
.catch(error => console.log(error));
async
或者使用/将其存储在变量中await
。
(async () => {
const lotManager = new LotManager();
const results = await lotManager.getLotById(420);
console.log(results);
}());
推荐阅读
- python - 查询列表理解
- angular - Angular - ngClass 在按钮单击之前已经存在
- javascript - SwiperJS - 上一个和下一个按钮不起作用
- c# - 在什么情况下,Azure Functions 会在消费计划上触发“CancellationToken”信号?
- java - jsp中的request.getParameter返回null或空字符串
- python - Python Pandas:如何用相应的列名填充空行?
- amazon-web-services - 如何在 aws lex 聊天机器人中获取欢迎消息
- ios - 我的应用程序版本高于以前但出现版本问题
- python - 调用子进程后脚本不继续
- c - 堆排序 - 数组结构 - C