如何使tx.executeSql()函数与async / await同步?

时间:2019-05-19 23:58:20

标签: javascript reactjs asynchronous async-await

如何使tx.executeSql(SQL, [], (tx, results)成为具有同步/等待功能的同步功能?

我想做这样的事情:

tx.executesql是异步的,所以我的closeDB()(closeDatabase())无法正常运行,因为事务正在进行中。

await tx.executeSql(sql, [], (tx, results)

但是它不起作用。

(请参阅输出)

这是我在输出末尾得到的警告:

C:\...name of proyect\node_modules\react-native\Libraries\Components\ScrollView\InternalScrollViewType.js:46 Possible Unhandled Promise Rejection (id: 0):
TypeError: error is not a function
TypeError: error is not a function
    at SQLitePlugin.close (blob:http://localhost:8081/7a5bb020-64e9-41f5-a654-e50e6b9f5827:93749:9)
    at _callee4$ (blob:http://localhost:8081/7a5bb020-64e9-41f5-a654-e50e6b9f5827:92942:54)
    at tryCatch (blob:http://localhost:8081/7a5bb020-64e9-41f5-a654-e50e6b9f5827:23006:19)
.
.
.
.
async componentDidMount() {


    console.log('*COMIENZA componentDidMount');
    await this.consultarBD();
    await this.openBD();

    console.log('DataUsuarios es: ' + this.state.dataUsuarios);
    await this.insertarDatos();
    await this.closeDatabase();

    console.log('*TERMINA componentDidMount');

  }
 insertarDatos = async () =>{
    console.log('COMIENZA insertarDatos');
     await db.transaction((tx) => {
       console.log('Comienza Transaction');
        for(let i in this.state.dataUsuarios){
          const sql = `INSERT INTO usuarios VALUES (
            '${this.state.dataUsuarios[i].id}', 
            '${this.state.dataUsuarios[i].nombre}',
            '${this.state.dataUsuarios[i].usuario}',
            '${this.state.dataUsuarios[i].password}',
            '${this.state.dataUsuarios[i].grupo}',
            '${this.state.dataUsuarios[i].faenas}'
          )`;
          console.log('antes de excute i es: ' + i);
          tx.executeSql(sql, [], (tx, results) => {
           console.log('dentro de executesql i es: ' + i);
            if(results.rowsAffected > 0){
              console.log('¡Datos insertados en BD!');
            }else{
              console.log('¡No se puedieron insertar datos en la BD!');
            }(error) => {
            console.log(error.message);
            }
          });
        }
        console.log('termina transaccion');
    });

    console.log('TERMINA insertarDatos');

  }

输出:



C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:22 COMIENZA insertarDatos
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:88 Comienza Transaction
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:88 antes de excute i es: 0
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:88 antes de excute i es: 1
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:88 antes de excute i es: 2
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:88 antes de excute i es: 3
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:90 termina transaccion
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:112 TERMINA insertarDatos
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:128 Cerrando database ...
C:\Users\josen\React-Projects\GeslubApp\src\Screen\DrawerScreens\index.js:7 cannot close: transaction is in progress
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:91 dentro de executesql i es: 0
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:93 ¡Datos insertados en BD!
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:91 dentro de executesql i es: 1
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:93 ¡Datos insertados en BD!
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:91 dentro de executesql i es: 2
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:93 ¡Datos insertados en BD!
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:91 dentro de executesql i es: 3
C:\Users\josen\React-Projects\GeslubApp\src\Screen\Login.js:93 ¡Datos insertados en BD!

3 个答案:

答案 0 :(得分:3)

异步/等待方式来制作executeSql()

async function example() {
  let db = await SQLite.openDatabase(
    database_name,
    database_version,
    database_displayname,
    database_size
  );

  await db.transaction(async tx => {
     var [tx, results] = await tx.executeSql("SELECT * from TableName;");
     var row = results.rows.item(0); //get the first row assumed existed.
  });

  await db.close();
}

答案 1 :(得分:0)

尝试像这样实现它,将其包装在一个Promise中,您应该可以使用await来调用此函数

  insertarDatos = () => {
    return new Promise((resolve, reject) => {
      db.transaction((tx) => {
        try {
          /* Successful transaction */
          /* Make sure to call resolve when the transaction has finished, maybe 
             db.transaction has a success callback
          */
          resolve()
        } catch (error) {
          /* Failed transaction */
          // if you reject any eventual errors, you can catch them when calling the function insertarDatos

          reject(error)
        }
      });
    })
  }

现在,如果那不起作用,则可能是您的forin有问题。如果是这种情况,检查此post可能会很有用。它具有async foreach的本地实现,可以如下实现:

await asyncForEach(userlist, async (user, index) => {
     // do something with user and index

     // you can use await here
})

答案 2 :(得分:0)

async getSqlitedata(): {
   const data = await dbconn.executeSql("SELECT * from TableName;",[]);
   if (data.rows.lenth >0) {
       console.log(data.rows);
   }
}

它将返回对象{rows: {…}, rowsAffected: 0, insertId: undefined}