首页 > 解决方案 > 如何在继续之前等待 cordova.plugins.sqlitePorter.exportDbToSql 完成?

问题描述

通过使用 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");

我期待日志的顺序是“成功”然后是“结束”,但它返回“结束”然后是“成功”

标签: javascriptandroidcordovaionic-framework

解决方案


更新

当您使用 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+,那么您可以在此处关注他们的文档。

打开命令行并输入

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'))

推荐阅读