【问题标题】:Getting a nested parameter return value in the wrapped function return在包装函数返回中获取嵌套参数返回值
【发布时间】:2021-05-21 18:33:12
【问题描述】:

我有一个场景,我需要从一个函数中获取返回值,该函数作为参数传递给另一个函数。我尝试了多种方法。但无法从 ProfileAction.js 文件中获取 returnValueCreateProfileComponent

// ProfileAction.js
export default (database) => {
  return {
    createProfile: async (createdProfile) => {
      const profileCollection = database.get("profiles");
      const { name, email } = createdProfile;
      try {
        await database.action(async () => {
          const returnValue = await profileCollection.create((profile) => {
            profile.name = name;
            profile.email = email;
          });
        });
      } catch (error) {
        console.log("createProfile", error);
      }
    },
  };
};

// CreateProfileComponent.js
const CreateProfileComponent = () => {
    const database = useDatabase();
    const profileAction = ProfileAction(database);
    const createdRecord = await profileAction.createProfile({
        name: "John Doe",
        email: "johndoe@gmail.com",
    });
}

最后我想要的是 CreateProfileComponent 中的 returnValue 值。函数 database.actions() 和 profileCollection.create() 使用来自第三方库 (WatermelonDB)

【问题讨论】:

    标签: javascript reactjs react-native watermelondb


    【解决方案1】:

    我不确定database.action 做了什么,但你应该在这个函数中返回一个值。如下:return await database.action(async () => {

    并在 catch 时抛出错误

    export default (database) => {
      return {
        createProfile: async (createdProfile) => {
          const profileCollection = database.get("profiles");
          const { name, email } = createdProfile;
          try {
            return await database.action(async () => {
              const returnValue = await profileCollection.create((profile) => {
                profile.name = name;
                profile.email = email;
              });
            });
          } catch (error) {
            console.log("createProfile", error);
            throw error;
          }
        },
      };
    };
    
    // CreateProfileComponent.js
    const CreateProfileComponent = () => {
        const database = useDatabase();
        const profileAction = ProfileAction(database);
        try {
            const createdRecord = await profileAction.createProfile({
                name: "John Doe",
                email: "johndoe@gmail.com",
            });
        } catch (e) {
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多