【问题标题】:How to wait cordova.plugins.sqlitePorter.exportDbToSql to complete before continuing?如何在继续之前等待 cordova.plugins.sqlitePorter.exportDbToSql 完成?
【发布时间】:2020-02-24 18:24:10
【问题描述】:

通过使用 SQLite Porter Cordova/Phonegap 插件,我正在尝试在继续执行代码之前创建应用程序数据库的备份文件。

但是,我无法这样做,因为它是异步的,无论我尝试什么,它总是在successFn 函数执行之前完成,即使successFn 是一种回调。

我已经尝试过使用承诺,等待/异步无济于事。我的最后一次尝试是使用 promise,如下例所示。

var successFn = function (sql, count) {
               console.log("Success")
            };
var promise = new Promise(function (resolve, reject) {
    cordova.plugins.sqlitePorter.exportDbToSql(db, {
         successFn: successFn
    })
});
promise.then(
    function () { return true; },
    function (erro) { return false;}
);
console.log("END");

我希望日志的顺序是“Success”然后“END”,但它返回“END”然后“Success”

【问题讨论】:

  • 您使用的是哪个版本的 Ionic?
  • 啊,抱歉打扰了。我正在使用 Ionic 1
  • 请查看更新后的答案

标签: javascript android cordova ionic-framework


【解决方案1】:

更新

当您使用 Ionic 1 时,您可以使用 promise 包装函数并使用它:

function exportDbToSql() {
  var deferred = $q.defer();
  cordova.plugins.sqlitePorter.exportDbToSql(db, {
    successFn: function(sql, count) { 
      deferred.resolve({sql: sql, count: count}) 
    }
  });
  return deferred.promise;
}

当你调用该函数时,它将是:

exportDbToSql().then(function(result) {
  console.log(result.sql);
  console.log(result.count);    
});

旧答案

如果您使用的是 Ionic 2+,那么您可以关注他们的文档here

打开命令行输入

ionic cordova plugin add uk.co.workingedge.cordova.plugin.sqliteporter
npm install @ionic-native/sqlite-porter

那么你可以这样使用它:

import { SQLitePorter } from '@ionic-native/sqlite-porter/ngx';


constructor(private sqlitePorter: SQLitePorter) { }

...

let db = window.openDatabase('Test', '1.0', 'TestDB', 1 * 1024);
// or we can use SQLite plugin
// we will assume that we injected SQLite into this component as sqlite
this.sqlite.create({
  name: 'data.db',
  location: 'default'
})
  .then((db: any) => {
    let dbInstance = db._objectInstance;
    // we can pass db._objectInstance as the database option in all SQLitePorter methods
  });


let sql = 'CREATE TABLE Artist ([Id] PRIMARY KEY, [Title]);' +
           'INSERT INTO Artist(Id,Title) VALUES ("1","Fred");';

this.sqlitePorter.importSqlToDb(db, sql)
  .then(() => console.log('Imported'))
  .catch(e => console.error(e));

在你的情况下,它应该像这样工作:

this.sqlitePorter.exportDbToSql(db)
  .then(() => console.log('success'))
  .catch(() => console.log('error'))

【讨论】:

  • 非常感谢,它真的帮助了我,不仅解决了这个问题,还让我了解了另一个困扰我一段时间的问题。
  • 太好了。很高兴为您提供帮助!
猜你喜欢
  • 2015-09-16
  • 1970-01-01
  • 2019-03-12
  • 2010-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 2020-02-25
相关资源
最近更新 更多