简体   繁体   中英

React Native - Assign value from promise to variable

I have a couple repositories containing database calls such as getUser and getUsers . Now I export those repositories as followed:

import { DatabaseBackend } from "../common/database";
import {
    userRepository as _userRepository,
    bookingRepository as _bookingRepository,
    pricingRepository as _pricingRepository,
} from "../common/repositories";

const backend = DatabaseBackend.ReactNative;

export const userRepository = _userRepository(backend);
export const bookingRepository = _bookingRepository(backend);
export const pricingRepository = _pricingRepository(backend);

This leads to me having to do things like this:

const fetchUserData = (uid: string) => {
        userRepository
            .then((u) => {
                u.getUser(uid)
                    .then((user: User) => {
                        if(!user) {
                            return;
                        }

                        setUser(user);
                    })
                    .catch((err) => {
                        logger.error("Something went wrong while fetching user information", err);
                    });
            })
            .catch(err => {
                logger.error("Something went wrong while fetching user information", err);
            });
    };

The intellisense says userRepository is:

const userRepository: Promise<{
    getUser: (id: string) => Promise<User>;
    getNanny: (id: string) => Promise<Nanny>;
    getNannies: () => Promise<Nanny[]>;
    getParent: (id: string) => Promise<Parent>;
    updateUser: (user: User) => Promise<void>;
}>

Is there a way how to assign the functions to userRepository without me having to do any then calls on it? I'd like to just being able to call userRepository.getUser() for example.

You can use async/await instead of then .

const fetchUserData = async (uid: string) => {
  try {
    const repo = await userRepository();
    const user: User = await repo.getUser(uid);
    if (!user) {
      return;
    }
    setUser(user);
  } catch (err) {
    logger.error("Something went wrong while fetching user information", err);
  }
};
  1. i would try and avoid having the userRepository coming from a Promise => try and have this resolved on some initialization phase of at least have memoization on its' value.
  2. use async/ await as suggested here already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM