[英]React Native - Assign value from promise to variable
I have a couple repositories
containing database calls such as getUser
and getUsers
.我有几个包含数据库调用的repositories
,例如getUser
和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:智能感知说userRepository
是:
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?有没有一种方法可以将函数分配给userRepository
而无需我对其then
任何调用? I'd like to just being able to call userRepository.getUser()
for example.例如,我希望能够调用userRepository.getUser()
。
You can use async/await instead of then
.您可以使用 async/await 代替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);
}
};
userRepository
coming from a Promise => try and have this resolved on some initialization phase of at least have memoization on its' value.我会尝试避免让userRepository
来自 Promise => 尝试在某些初始化阶段解决这个问题,至少对其值进行记忆。async/ await
as suggested here already.按照这里的建议使用async/ await
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.