javascript - 如何在继续之前等待 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");
我期待日志的顺序是“成功”然后是“结束”,但它返回“结束”然后是“成功”
解决方案
更新
当您使用 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'))
推荐阅读
- java - 如何使用Java替换Windows目录中多个文件夹名称中的字符串
- cplex - CPLEX OPL 错误 5002 错误
- cuda - 在 Cuda 中分配对象的问题
- java - 使用注解和父抽象 bean 声明一个 bean(在 XML 文件中声明)
- javascript - 导致 for 循环重复太多次 - 删除重复的 JS
- c++ - 有没有办法在两个共享对象之间使用相同的全局变量?
- javascript - 在应用 appendto 后将表代码的最后一个 td 更改为新代码
- ruby-on-rails - Rspec 控制器分配没有按预期工作
- mysql - 使用 sqlmap 对数据库进行指纹识别
- ruby-on-rails - 管理员如何使用 link_to 更改布尔用户字段?