简体   繁体   English

React Native - 将 promise 的值分配给变量

[英]React Native - Assign value from promise to variable

I have a couple repositories containing database calls such as getUser and getUsers .我有几个包含数据库调用的repositories ,例如getUsergetUsers 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);
  }
};
  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.我会尝试避免让userRepository来自 Promise => 尝试在某些初始化阶段解决这个问题,至少对其值进行记忆。
  2. use async/ await as suggested here already.按照这里的建议使用async/ await

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 Promise 分配给 React 中的变量 - Assign Promise To Variable In React 将从诺言返回的值分配给全局变量 - Assign a value returned from a promise to a global variable 是否可以使用react.js将promise数据值分配给外部变量 - Is it possible to assign promise data value to outside variable with react.js 将成功承诺解析的值分配给外部变量 - Assign value from successful promise resolve to external variable 从反应本机asyncStorage获取实际值而不是promise - Getting actual value from react-native asyncStorage instead of promise 从 promise 获取值反应原生并结合到 Axios header - Get value from promise react native and cominbing to Axios header React Native - 从 promise 中的事件侦听器返回值 - React Native - Return value from event listener in a promise React-Native将从url获取的JSON对象分配给变量 - React-Native assign a JSON Object fetched from url to a variable 在promise中,我想将值(值本身来自另一个promise)分配给将在该promise外使用的变量 - Inside a promise I want to assign value(the value itself comes from some another promise ) to a variable which will be used outside of that promise 来自Promise React Native的结果 - Result from promise React Native
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM