我在尝试了解async函数在React Native中的工作方式时有些挣扎。

在此示例中,我通过异步调用来调用sqllite db调用,并获取heightstandard的值,并将这两个值作为一个称为result的对象返回。

如下面的控制台输出所示,值在sqllite db中存在。

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;

      }

设备和控制台的输出

javascript -  react  native : Handling Async calls to sqllite db-LMLPHP

javascript -  react  native : Handling Async calls to sqllite db-LMLPHP

最佳答案

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

另外,函数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);
  });
}

09-18 18:19