两个异步函数同时操作rdbstore的数据竞争问题处理,该如何避免?
私信场景,两个接口分别获取商品信息和联系人头像昵称,分别在两个异步函数发起请求,之后读取数据库,并更新信息,但是测试发现数据有竞争现象,导致数据被覆盖。
func1() {
let user = await MsgCenterContactDB.getContactByUid(uid);
user.name = xxx;
await MsgCenterContactDB.insertOrUpdate(user);
}
func2() {
let user = await MsgCenterContactDB.getContactByUid(uid);
user.headPic = xxx;
await MsgCenterContactDB.insertOrUpdate(user);
}
这两个函数都是异步的,导致数据产生了错乱,最终headPic或者name为空
关于此问题,官方有约束,同一时间只能有一个写操作,参考链接:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/data-persistence-by-rdb-store-V5
请确认是否使用API是10? 如果是的话,可通过指定冲突解决模式,来解决此问题,参考链接:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-data-relationalstore-V5\#update10