如何在 Realm.open 函数中调用 Await 函数?

How to call Await functions inside Realm.open function?

我正在尝试将 Realm 数据库集成到我的项目中

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);
    }
  };

但它表明我不能在异步函数外调用 await,但如果数据库为空,我只需要从 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 函数 -> 减少嵌套:)