1

我是 React-Native 的新手,我对如何拥有一个可以由文件中的所有函数访问的变量而不是在一个类中感到困惑。

我的问题是我在 taskFour() 中分配了存储空间,并且我希望在 runDemo() 中返回该值,但是由于某种原因,当我在 runDemo() 中的 console.log(storage) 中返回未定义时!

我已经定义了一个帮助文件,其中包含一堆相互调用的函数。

助手.js

import React from 'react';
import SQLite from 'react-native-sqlite-storage';

let db;
let storage;

function runDemo() {
  loadAndQueryDB();
 //Suppose to return value assigned in queryPeopleSuccess but console logs 'undefined'
  console.log(storage);
  return storage;
}

//    Sends an update saying that Database was successfully opened
function openCB() {
  console.log("Success Opening DB");
}

//      Sends an update with error message and returns FALSE
function errorCB(err) {
  console.log("SQL Error: ", err);
  return false;
}

/** 2. Called when runDemo is called **/
/*   assigns variable 'db' to opened Database */
/*   Calls queryPeople(db) */
function loadAndQueryDB() {
  console.log("Opening Database...: ");
  
  db = SQLite.openDatabase({ name: "users.db", createFromLocation: 1}, openCB, errorCB);
  queryPeople(db);
}

/** 3. Called when loadAndQueryDB is called **/
/*    Get the DB and applies a SQL call that if successful will call queryPeopleSuccess*/
function queryPeople(db) {
  console.log("Executing employee query...");
  //Execute a database transaction.
  db.transaction((tx) => {
    tx.executeSql('SELECT * FROM users', [], queryPeopleSuccess, errorCB);
  });

}

function queryPeopleSuccess(tx, results) {
  var len = results.rows.length;
  let localArray = [];
  //Go through each item in dataset
  for (let i = 0; i < len; i++) {
    let row = results.rows.item(i);
    localArray.push(row);
  }

  storage = localArray;
}

export {
  runDemo,
}

我认为通过在函数之外分配“存储”可以使其成为该文件中所有函数可访问的变量,而不使其成为全局变量。此外,我的一个限制是我不能从 queryPeopleSuccess 一路返回存储到 runDemo,因为这些函数中的函数不应该有返回值!

有人可以指出我如何在一个文件中拥有一个变量,而该变量不需要在一个可以由该文件中的函数访问和编辑的类中?

已编辑:为清晰和错别字而编辑。原来我的代码的问题是由于异步!

4

3 回答 3

1

您的问题与Javascript中的异步有关。

您当前的程序(脚本)使用同步机制从上到下执行,并且您没有value为您的变量分配任何初始值storage。所以函数runDemo返回默认值undefined

要解决您的问题,您需要将您的转换runDemo为异步函数。

let storage;

async function runDemo() {
    await taskOne();
    //Suppose to return value assigned in taskFour but console logs 'undefined'
    console.log(storage);
    return storage;
}


function taskOne() {
    taskTwo();
}

function taskTwo() {
    taskFour();
}

let localArray = 20;

function taskFour() {

    storage = localArray;
    //Here storage is assigned properly and outputs the data I want
    console.log(storage);
}
runDemo()

于 2020-06-29T22:45:59.390 回答
1

您的问题是,runDemo之前已经返回很久了,queryPeopleSuccess甚至正在写入storage. 所以,你是在它被写之前阅读它,并且由于信息不能及时返回,你会得到undefined. 基本上你有这个问题。

您可以通过使用异步函数来大大简化您的代码:

import SQLite from 'react-native-sqlite-storage'

export async function runDemo () {
  console.log('Opening Database...: ')

  try {
    // This one is tricky, because it seems the library synchronously
    // returns the db instance, but before that it calls the success or
    // error callbacks (without passing the instance).
    const db = await new Promise((resolve, reject) => {
      const db = SQLite.openDatabase(
        { name: 'users.db', createFromLocation: 1 },
        // The trick here is that in the success case we wait for openDatabase
        // to return so that db will be assigned and we can resolve the promise
        // with it.
        () => setTimeout(() => resolve(db), 0),
        reject
      )
    })
    console.log('Success Opening DB')

    console.log('Executing employee query...')
    // Execute a database transaction.
    const results = await new Promise((resolve, reject) => {
      db.transaction(tx => {
        tx.executeSql(
          'SELECT * FROM users',
          [],
          (tx, results) => resolve(results),
          reject
        )
      })
    })

    const localArray = []
    // Go through each item in dataset
    for (let i = 0; i < results.rows.length; i++) {
      localArray.push(results.rows.item(i))
    }
    return localArray
  } catch (e) {
    console.log('SQL Error: ', e)
    return false
  }
}

然后你会在另一个异步函数中调用runDemoas ,或者以其他方式调用。console.log(await runDemo())runDemo().then(results => console.log(results), err => console.error(err))

于 2020-06-29T22:50:07.710 回答
1

taskFour从来没有叫过?您taskThreetaskTwo.

于 2020-06-29T22:24:19.933 回答