异步函数返回数组为空

时间:2019-08-18 22:37:19

标签: javascript sqlite react-native asynchronous

我正在使用sqlite3从本地testDB获取数据。提取和解析是在dataquery.js中完成的。 getAllPoints应该获取所有数据库记录。在camOverLay.js类中,异步testcallfunctions使用await来从dataquery.js中的getAllPoints实现诺言。当我尝试打印出异步函数的返回值时,尽管有十个项目,但显示为null。似乎等待者不会等到兑现诺言。

[![debugger][1]][1]
dataquery.js 

import SQLite from "react-native-sqlite-storage";

const db = SQLite.openDatabase({name:"testDB", createFromLocation:1})

function parsePoints(row){
  var longitude = row.data_longitude.slice(3,-3);
  var latitude  = row.date_latitude.slice(3,-3);
  var price     = row.price.slice(1);
  var address   = row.address;

  const obj = {longitude:longitude,
               latitude:latitude,
                address: address,
               price:  price}
  return obj
}

module.exports = {
  getAllPoints :async function(){
    return new Promise((res, rej)=>{
      var agg_data = [];
      SQLite.DEBUG(true);
      SQLite.enablePromise(true);
      db.transaction(tx=>{
        tx.executeSql(
          'SELECT * FROM listinginfo LIMIT 10',
          [], (tx, results)=>{
            var len = results.rows.length;
            for(let i = 0; i < len ; i++){
              let row = results.rows.item(i);
              obj = parsePoints(row);
              console.log("this is obj")
              console.log(obj)
              console.log(obj.price)
              agg_data.push(obj);
              console.log("this is agg_data");
              console.log(agg_data.length);
            }
            });
       });
      res(agg_data);
      return res
    });
  }
}

camOverLay.js

import React from 'react';
import { StyleSheet, FlatList,TouchableOpacity,Text, ListView,View, Button, Alert } from 'react-native';
import dataquery from './../utils/dataquery';

function callfunction(){
console.log("this is a test call for utils");

}
export default class camOverLay extends React.Component {
  componentDidMount(){
   this.testcallfunction()
   // callfunction()
  }
  async testcallfunction(){
    let p1 = await dataquery.getAllPoints();
    console.log("this is the p1")
    console.log(p1)
    console.log(p1.length);
  }
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>AR Screen</Text>
      </View>
    );
  }
}

0 个答案:

没有答案