在 react-native-sqlite-storage 中 React Native Async Await [英] React Native Async Await in react-native-sqlite-storage

查看:75
本文介绍了在 react-native-sqlite-storage 中 React Native Async Await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 React Native 并不陌生.在开始之前,我已经阅读了很多教程.我正在尝试在我的应用程序中创建商店,以便在需要时可以通过应用程序的屏幕访问.

I am little new to React native. I have gone through lot of tutorials before starting up. I am trying to make stores in my app which can be accessed by Screens of the app when required.

这是我的文件结构.

  1. index.ios.js
  2. /app/index.js
  3. /app/store/database.js
  4. /app/store/userStore.js

index.ios.js

import { AppRegistry } from 'react-native';
import App from './app/index';
AppRegistry.registerComponent('AwesomeProject', () => App);

/app/index.js

import React, { Component} from 'react';
import {
  Text,
  View,
} from 'react-native';
import userStore from './store/userStore';
import ViewBackground from './components/ViewBackground';


class App extends Component {
        constructor(props){
            super(props);
            this.isLoggedIn = true;     
        }

        componentDidMount() {       
            this.fetchUsers().done();
        }

        async fetchUsers(){
            console.log('Before User Fetch');
            var result = await userStore.getAllUsers();
            console.log('After User Fetch');
        }

        render() {
            if(this.isLoggedIn){
                return this.loggedInView();
            }else{
                return this.loggedOutView();
            }
        }

        loggedInView(){
            return <ViewBackground>

            </ViewBackground>
        }

        loggedOutView(){
            return <View>
            <Text>Hi, This is logged Out view </Text>
            </View>
        }
    }

    export default App;

/app/store/userStore.js

从'react'导入React;从'./database'导入数据库;

import React from 'react'; import database from './database';

    class UserStore{

        async getAllUsers(){
            let query = {
                type: 'SELECT',
                sql: 'SELECT * FROM Users',
                vals: [],
            }
            let queries = [query];
            console.log('in store before');
            let dbResult = await database.runQuery(queries);        
            console.log('in store after');
            return dbResult;        
        }
    }

    const userStore = new UserStore;

    export default userStore;

/app/store/database.js

    'use strict';
    import React from 'react';
    import SQLite from 'react-native-sqlite-storage';
    SQLite.enablePromise(true);

    var database_name = "test.db";
    var database_version = "1.0";
    var database_displayname = "Test";
    var database_size = 1024 * 1024 * 10;

    class Database  {

        constructor(){
            SQLite.openDatabase(database_name, database_version, database_displayname, database_size).then(this.dbOpenSuccess).catch(this.dbOpenError);
        }

        dbOpenSuccess(dbInstance){
            this.conn = dbInstance;
        }

        dbOpenError(err) {

        }

        getConnection() {
            return this.conn;
        }

        setUpDatabase(){
            let queries = [
            'CREATE TABLE IF NOT EXISTS Users (user_id INTEGER PRIMARY KEY, f_name VARCHAR(64), l_name VARCHAR(64), email_id VARCHAR(128), mobile VARCHAR(10))'
            ];
            this.conn.transaction( tx => {
                queries.map( q => {
                    tx.executeSql(q, [], res => {}, err => {});
                });
            });
        }

        async runQuery(queries) {
            await this.conn.transaction(tx => {
                return Promise.all(queries.map(async (q) => {
                    try {
                        let results = null;
                        switch(q.type){
                            case 'SELECT':                      
                            results = await tx.executeSql(q.sql, q.vals);
                            console.log('Query', q, 'Executed. results:', results);
                            break;
                        }

                    } catch(err) {
                        console.log('Something went wrong while executing query', q, 'error is', err);
                    }
                }));
            });
            return false;
        }

        closeDatabase(){
            this.conn.close().then(this.dbCloseSuccess).catch(this.dbCloseError);
        }

        dbCloseSuccess(res) {

        }

        dbCloseError(err){

        }
    }

    const dbInstance = new Database();

    dbInstance.setUpDatabase();

    export default dbInstance;

正如您从 /app/index.js 中的代码所看到的,我试图从 userStore.js 中获取用户,最终将调用database.js 文件以从数据库中检索用户.当我尝试从数据库获取用户时,我想暂停代码的执行,因此我尝试使用 async/await.

As you can see from the code that in /app/index.js, I am trying to fetch the users from the userStore.js which will finally call the database.js file to retrieve the users from the database. I want to pause the execution of the code when I am trying to fetch the users from DB, so I have tried to use async/await.

如果你能在代码中看到我已经使用 console.log() 来检查执行是暂停还是继续.没有一个 async/await 在任何文件中工作.在完成所有 console.log 后,我得到了响应.

If you can see in the code I have used console.log() to check whether the execution pause or it continues. None of the async/await is working in any of the file. I am getting response after all the console.log is done.

我想等待从数据库接收数据的时间.请给一些专家建议,我哪里出错了.提前致谢.

I want to wait for the time till I receive the data from the DB. Please give some expert advise, where I am going wrong. Thanks in advance.

推荐答案

需要将其包装在一个 Promise 中,然后在 sql 执行完成时解析结果.

You need to wrap it in a Promise, then resolve the result when sql execution is done.

例如

async () => {
  return new Promise((resolve, reject) => {
    db.transaction(tx => {
      tx.executeSql('SELECT * FROM users;', [], (tx, results) => {
        const { rows } = results;
        let users = [];

        for (let i = 0; i < rows.length; i++) {
          users.push({
            ...rows.item(i),
          });
        }

        resolve(users);

      });
    });
  });

}

这篇关于在 react-native-sqlite-storage 中 React Native Async Await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆