无法在 react-native 中异步执行 sqlite db 查询
2020-12-01
1294
我有一个组件,需要依次执行几个查询。我使用了承诺,但似乎不起作用/我无法这样做。这是我的组件的一部分:
export default function AuthWrapper() {
useEffect(() => {
// creating app_tokens table if not exist
console.log('before first query');
new Promise((resolve) => {
db.transaction(function (txn) {
txn.executeSql(
"SELECT name FROM sqlite_master WHERE type='table' AND name='app_tokens'",
[],
function (tx, res) {
console.log('first query executed');
resolve(res);
},
function(error) {
console.log(error);
}
);
});
});
console.log('before second query');
// creating users table
new Promise((resolve) => {
db.transaction(function (txn) {
txn.executeSql(
"SELECT name FROM sqlite_master WHERE type='table' AND name='users'",
[],
function (tx, res) {
console.log('second query executed');
resolve(res);
},
function(error) {
console.log(error);
}
);
});
});
console.log('before third query');
// creating institute_details table
new Promise((resolve) => {
db.transaction(function (txn) {
txn.executeSql(
"SELECT name FROM sqlite_master WHERE type='table' AND name='institute_details'",
[],
function (tx, res) {
console.log('third query executed');
resolve(res);
},
function(error) {
console.log(error);
}
);
});
});
}, []);
}
当我运行此代码时,日志显示如下:
before first query
before second query
before third query
first query executed
second query executed
third query executed
但它应该是这样的:
before first query
first query executed
before second query
second query executed
before third query
third query executed
有人能帮我解决我遗漏的内容吗!
仅供参考:我正在使用
"react": "16.11.0",
"react-native": "0.62.2",
"react-native-sqlite-storage": "^5.0.0",
1个回答
你问错了,按照我的说法,你想要同步,通过查看你想要的输出。
对于那个异步 - await 就在那里。
我不知道你为什么使用承诺,但是,是的,使用你现在拥有的代码,你可以做这样的事情,
const myFirstFunction = () => {
return new Promise((resolve) => {
db.transaction(function (txn) {
txn.executeSql(
"SELECT name FROM sqlite_master WHERE type='table' AND name='app_tokens'",[],
function (tx, res) {
console.log('first query executed');
resolve(res);
},
function (error) {
console.log(error);
},
);
});
});
};
const mainFunction = async () => {
console.log('before first query');
await myFirstFunction();
// ... similarlly create and call other functions here
// ... creating different methods will be easy to maintain
};
useEffect(() => {
mainFunction();
}, []);
Jaydeep Galani
2020-12-01