android - 如何在 Realm.open 函数中调用 Await 函数?
问题描述
我试图将 Realm db 集成到我的项目中
Model File :
export const CHAT_LIST_SCHEMA = {
name: 'ImList',
properties: {
name: 'string',
rid: 'string',
lastMessage: 'string',
time: 'string',
},
};
Code :
init = async () => {
try {
Realm.open({ schema: CHAT_LIST_SCHEMA }).then((realm) => {
let cachedData = realm.objects('ImList');
console.log('Cached Data', cachedData);
if (cachedData === '') {
console.log('called123');
this.setState({ data: cachedData });
} else {
console.log('called');
const result = await RocketChat.getIMlist(); // API Call
const data = await RocketChat.getRoomsList(result); // Filtering
realm.write(() => {
data.map((items) => {
realm.create('ImList', {
name: items.name,
rid: items.rid,
lastMessage: items.lastMessage,
time: items.time,
});
});
});
}
});
} catch (error) {
console.log(error);
}
};
但它表明我不能在异步函数之外调用等待,但如果数据库为空,我只需要从 API 获取数据。该怎么办?
解决方案
您将 async 放在了错误的功能上。等待异步方法的是.then
语句内部的箭头函数,因此它应该如下所示:
init = () => {
try {
Realm.open({ schema: CHAT_LIST_SCHEMA }).then(async (realm) => {
let cachedData = realm.objects('ImList');
console.log('Cached Data', cachedData);
if (cachedData === '') {
console.log('called123');
this.setState({ data: cachedData });
} else {
console.log('called');
const result = await RocketChat.getIMlist(); // API Call
const data = await RocketChat.getRoomsList(result); // Filtering
realm.write(() => {
data.map((items) => {
realm.create('ImList', {
name: items.name,
rid: items.rid,
lastMessage: items.lastMessage,
time: items.time,
});
});
});
}
});
} catch (error) {
console.log(error);
}
};
顺便提一句。您也可以等待 Realm.open 函数 -> 减少嵌套 :)
推荐阅读
- python - 尝试下载 edx 视频但出现错误
- django - 如何覆盖 Djoser 基本端点用户/我
- sql - 为什么使用 INSERT INTO 和 VALUE 子句在 phpmyadmin 中出现错误?
- javascript - 无法在 Javascript 字典中添加键值对
- python - 图像下载为空白,没有大小
- feature-extraction - 灰度共现矩阵
- node.js - 节点版本错误:Node Sass 找不到当前环境的绑定:OS X 64-bit with Node.js 12.x ~
- python - VS 代码 - Python“运行”
- javascript - 实现css的最佳方式
- .net-core - Azure 服务总线 - 使用 ServiceBusReceiver 时自动更新消息锁