javascript - react native : Handling Async calls to sqllite db

标签 javascript reactjs asynchronous react-native expo

我在尝试理解 async 函数在 React Native 中的工作方式时遇到了一些困难。

在此示例中,我通过异步调用调用 sqllite 数据库调用并获取 heightstandard 的值,并将这两个值作为名为 的对象返回结果

值存在于 sqllite 数据库中,可以在下面显示的控制台输出中看到。

componentDidMount生命周期方法调用的方法是异步方法。

可以看出,我正在使用 await 来等待实际执行(也就是从 sqllite 获取数据)完成。

第 X 行始终返回未定义。

Y 行似乎根本没有执行,因为状态从初始值 100 和“asasd”根本没有改变。

我已经看过代码,但不确定我在这里遗漏了什么。

有人可以看一下并告诉我吗?

App.js

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import {
  dropLogsTable,
  createLogsTable,
  getProfileHeightStandardfromDB,
  getProfileHeightStandardPremade,
  saveLogsRecord
} from '../src/helper';

export default class App extends Component {
  state = {
    logarray: [],
    profileobject: {profileheight: 100, profilestandard: "asasd"},

  };


  componentDidMount() {

    dropLogsTable();
    createLogsTable();
    this.fetchProfileData();


  }

  async fetchProfileData() {
    console.log('Before Profile Fetch');
    const result = await getProfileHeightStandardfromDB();
    console.log('After Profile Fetch');
    console.log('Height : '+result.profileheight);
    console.log('Standard: '+result.profilestandard);
    return result; //Line X
    this.setState({profileobject:result}); //Line Y
  }

  render() {
    return (
      <View>
        <Text>This is a test</Text>
        <Text>Profile Height : {this.state.profileobject.profileheight} </Text>
        <Text>Profile Standard : {this.state.profileobject.profilestandard}</Text>
      </View>
    );
  }
}

helper.js

import { SQLite } from 'expo';

const db = SQLite.openDatabase({ name: 'swlt.db' });

let profileheight, profilestandard;

export function getProfileHeightStandardfromDB()
          {
        db.transaction(
          tx => {

            tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, { rows }) =>
              {
                //console.log(rows);
                console.log(rows);

                //console.log(parseFloat(rows._array[0].metricheight));
                profileheight = parseFloat(rows._array[0].metricheight);
                profilestandard = rows._array[0].standard;
                console.log('Profileheight ===>'+profileheight);
                console.log('Profilestandard ===>'+profilestandard);
              }
            );
          },
          null,
          null
        );

        const profileobject = {profileheight, profilestandard};
        console.log(profileobject);
        return profileobject;

      }

设备和控制台的输出

enter image description here

enter image description here

最佳答案

您似乎在 return 语句之后有 this.setState; return 语句之后不会执行任何代码。只需将 this.setState 调用放在返回 block 之前

此外,函数 getProfileHeightStandardfromDB() 需要是一个 async 函数或需要返回一个 Promise。目前该方法不返回 Promise,因此没有必要等待它。所以这是你需要做的

function getProfileHeightStandardfromDB() {
  return new Promise((resolve, reject) => {
    db.transaction(
      tx => {
        tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, { rows }) => {
          //console.log(rows);
          console.log(rows);

          //console.log(parseFloat(rows._array[0].metricheight));
          profileheight = parseFloat(rows._array[0].metricheight);
          profilestandard = rows._array[0].standard;
          console.log('Profileheight ===>'+profileheight);
          console.log('Profilestandard ===>'+profilestandard);

          // what you resolve here is what will be the result of
          // await getProfileHeightStandardfromDB(); 
          resolve({ profileheight, profilestandard });
      });
    }, null, null);
  });      
}

关于javascript - react native : Handling Async calls to sqllite db,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47345000/

相关文章:

javascript - 播放期间跳过部分YouTube视频

javascript - 避免在 $.expr [':' ] 中的数组和对象文字中尾随逗号 - javascript

javascript - 使用 Angular 服务/工厂的 Setter 和 getter

reactjs - fetch 总是通过 OPTIONS 方法

reactjs - 如何在 Jest 测试期间初始化 React usecontext 状态值?

c# - c#中线程模式的正确回调

javascript - 用于匹配以逗号分隔的特定数字的正则表达式

javascript - 如何在 Javascript 中将 JSON 对象解析为指定的类型?

.net - Control.EndInvoke 为异常重置调用堆栈

javascript - for循环中的异步回调失败