![](/img/trans.png)
[英]My log not executed after the sqlite database transaction? why its executes before the db transaction?
[英]Why statement executes before db transaction?
在下面的代碼中,我想在我的代碼中完成所有數據庫事務后設置 state 域,請任何人告訴我完美地完成該操作。
我調用下面的方法來設置新的域數組
setFavorites() {
var arr = this.state.domains.map((item, index) => {
new Promise((resolve, reject) => {
db.transaction((tx) => {
try {
tx.executeSql(
'SELECT * FROM table_favorites WHERE id=' + item.product_id, [],
(tx, results) => {
var len = results.rows.length;
if (len > 0) { item.isFavorite = true } else { item.isFavorite = false }
}
);
resolve()
} catch (error) {
reject(error)
}
});
})
return { ...item }
})
this.setState({ domains: arr })
}
我建議使用 Promise.all() 並在里面使用。然后使用 setState()
就像是:
編輯:this.state.domains 是 object 的數組,因此不應直接更新
setFavorites() {
Promise.all(
this.state.domains.map(item => {
return new Promise((resolve, reject) => {
db.transaction((tx) => {
try {
tx.executeSql(
'SELECT * FROM table_favorites WHERE id=' + item.product_id, [],
(tx, results) => {
var len = results.rows.length;
if (len > 0) {
resolve({...item, isFavorite = true})
}
else {
resolve({...item, isFavorite = false})
}
}
);
} catch (error) {
reject(error)
}
});
})
})
)
.then(arr => this.setState({ domains: arr }))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.