首页 > 解决方案 > 如何在 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 获取数据。该怎么办?

标签: androidiosreact-nativerealm

解决方案


您将 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 函数 -> 减少嵌套 :)


推荐阅读