首页 > 解决方案 > 从另一个类中的函数获取返回值

问题描述

如何获取另一个类中函数的返回值:

我有一个带有一些 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 请求函数结果发送给我的班级的最佳方法是什么?现在我可以与函数交互,但无法获得返回值(我理解为什么这段代码不起作用,它只是为了解释我想要的)。

谢谢你的帮助!

标签: javascriptsqlitereact-nativeexpo

解决方案


将 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);
                }
            );
        });
    });
}

现在您可以使用 athencatch语法获取值。

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);
}());

推荐阅读