【问题标题】:Function not returning variable in ES6 [duplicate]ES6中的函数不返回变量[重复]
【发布时间】:2019-03-30 16:11:16
【问题描述】:

我试图在 ES6 中返回一个变量,其中数据由 Expo 中的 SQLLite 事务加载到其中,但我不确定如何执行此操作,因为它总是返回 null。

import {SQLite} from 'expo';
import React from 'react';
const db = SQLite.openDatabase('db.db');
class CoreApp extends React.Component{

getLoginTokens = () => {
    var result = [];
    db.transaction(success, tx => {
        tx.executeSql(
            `SELECT token FROM tokens LIMIT 1;`,
            [],
            (_, { rows: { _array } }) => {
                result = _array;
            }
        );
    });
};
}

class SelectTour extends React.Component {
    render() {
        //
        CoreApp.getLoginTokens();
    }
}

当 getLoginTokens 运行时,我想返回结果,但每次我 console.log 时,结果都是未定义的。

如果我在 tx.executeSql 的范围内并且我运行 console.log(_array) 它会显示一个完整的数组。

在 ES6 中,如何正确设置结果?我目前正在使用result = _array;但结果并未在事务之外设置。

【问题讨论】:

  • 你需要一个return 声明-
  • 也试过了,没有运气。
  • 但是,有异步,所以你不能同步返回结果
  • 随意发布答案,我会向你学习,其他许多人也会这样:)
  • erm,我想不出答案,因为 a) 我看不出你如何使用(打电话)getLoginTokens 和 b) 不知道 dbsuccess 是什么它们似乎是已经存在且没有上下文的东西,真的无济于事

标签: javascript sqlite ecmascript-6 expo


【解决方案1】:

使用承诺:

getLoginTokens = () => new Promise((resolve, reject) => {
    db.transaction(success, tx => {
        tx.executeSql(
            `SELECT token FROM tokens LIMIT 1;`,
            [],
            (_, { rows: { _array } }) => {
                resolve(_array);
            }
        );
    });
});

现在 getLoginTokens 返回一个 Promise,您可以按常规方式使用它

getLoginTokens.then(results => console.log(results));

老派回调

getLoginTokens = cb => {
    db.transaction(success, tx => {
        tx.executeSql(
            `SELECT token FROM tokens LIMIT 1;`,
            [],
            (_, { rows: { _array } }) => {
                cb(_array);
            }
        );
    });
};

用法

getLoginTokens(results => console.log(results));

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    相关资源
    最近更新 更多