新的承诺不适用于db.transaction

时间:2019-06-18 21:33:31

标签: javascript async-await react-native-sqlite-storage

我正在React-native中使用sqlite(react-native-sqlite-storage),现在要关闭数据库时,promise存在问题:

    this.dataUsuarios= await fetchData(this.url);    
    db = await openDB();
    await this.insertarDatos();
    db.close();

问题是执行db.close时给我一个问题,因为this.insertarDatos()仍在处理,但idk为什么。我认为我的新诺言应该行得通!

insertarDatos = () =>{
    return new Promise((resolve, rejection)=>{
      db.transaction((tx) => {
          for(let i in this.dataUsuarios){
            const sql = `INSERT INTO usuarios VALUES (
              ${this.dataUsuarios[i].id}, 
              '${this.dataUsuarios[i].nombre}',
              '${this.dataUsuarios[i].usuario}',
              '${this.dataUsuarios[i].password}',
              ${this.dataUsuarios[i].grupo},
              '${this.dataUsuarios[i].faenas}'
            );`;
            tx.executeSql(sql, [],  this.successCB(i), this.errorCB);
          }
      },resolve,rejection);
    });
  }

1 个答案:

答案 0 :(得分:0)

在撰写本文时,db.transaction首先将错误回叫,而您正在传递resolve

这是一个示例:

// sqlite transactions don't play with promises nicely.
// the fn param here shouldn't use promises.
const transactional = async (fn: (tx: Transaction) => void) => {
  const db = await getDb();
  const x = new Promise((resolve, reject) => {
    const trans = db.transaction(fn, (e) => {
      console.log('transaction failed ')
      reject(e)
    },
    () => {
      console.log('transaction finished ok')
      resolve();
    });
  });
  await x;
};