[英]Why statement executes before db transaction?
in below code, I want to set state domains after all the DB transaction completed in my code, please any one tell me to do that operation perfect.在下面的代码中,我想在我的代码中完成所有数据库事务后设置 state 域,请任何人告诉我完美地完成该操作。
I calling below method to set the new domains array我调用下面的方法来设置新的域数组
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 })
}
I would recommend use Promise.all() and inside the.then use the setState()我建议使用 Promise.all() 并在里面使用。然后使用 setState()
something like:就像是:
EDIT : this.state.domains is array of object, so it should not be updated directly编辑: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.