我正在尝试获取ResultSet from the executeSql库的react-native-sqlite-storage
函数,但得到TypeError: Cannot read property '0' of undefined
。
executeSql
函数应返回一个Promise<[Transaction, ResultSet]>
,但我似乎无法正确地实现销毁。
我的代码:database.ts
:
let conn = SQLite.openDatabase({name: DATABASE_NAME, location: 'default'})
export default class Db {
static async getConn() {
return await conn
}
static async getTransaction() {
return new Promise<Transaction>(async (resolve,reject) => {
const conn = await this.getConn()
conn.transaction((transaction: Transaction) => {
resolve(transaction)
})
})
}
static async executeSql(sqlStatement: string, args?: any[]) {
return new Promise<ResultSet>(async (resolve,reject) => {
const transaction = await this.getTransaction()
const [tr, results] = await transaction.executeSql(sqlStatement, args) // ??
resolve(results)
})
}
}
已编译:
Db.executeSql = function (sqlStatement, args) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var transaction, _a, tr, results;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.getTransaction()];
case 1:
transaction = _b.sent();
return [4 /*yield*/, transaction.executeSql(sqlStatement, args)];
case 2:
_a = _b.sent(), tr = _a[0], results = _a[1]; // <= ERROR HERE: TypeError: Cannot read property '0' of undefined
resolve(results);
return [2 /*return*/];
}
});
}); })];
});
});
};
答案 0 :(得分:0)
查看代码(https://github.com/andpor/react-native-sqlite-storage/blob/master/lib/sqlite.core.js#L449),transaction.executeSql
不会返回Promise。它实际上什么也不会返回。
似乎该方法也接受success
和error
回调,因此您的代码应类似于:
static async executeSql(sqlStatement: string, args?: any[]) {
const transaction = await this.getTransaction();
const [tr, results] = await new Promise<ResultSet>(
(resolve,reject) =>
transaction.executeSql(sqlStatement, args,
(t, r) => resolve([t, r]),
(err) => reject(err)
)
);
return results;
}