[英]How to wait cordova.plugins.sqlitePorter.exportDbToSql to complete before continuing?
通過使用 SQLite Porter Cordova/Phonegap 插件,我試圖在繼續執行代碼之前創建應用程序數據庫的備份文件。
但是,我無法這樣做,因為它是異步的,無論我嘗試什么,它總是在successFn function 執行之前完成,即使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 並使用它:
function exportDbToSql() {
var deferred = $q.defer();
cordova.plugins.sqlitePorter.exportDbToSql(db, {
successFn: function(sql, count) {
deferred.resolve({sql: sql, count: count})
}
});
return deferred.promise;
}
當您調用 function 時,它將是:
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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.