【问题标题】:How to use object of type Promise <string | null> as a string如何使用 Promise <string | 类型的对象null> 作为字符串
【发布时间】:2021-05-18 11:00:40
【问题描述】:

大家好,我对打字稿中的类型有疑问。 我正在使用 micro orm 从我正在使用此代码的数据库中获取数据

const user = (await orm).em.findOne(User, { username: options.username });

它回来了

user: Promise<string | null>

我的问题从这里开始我必须将此对象用作表单中的字符串

user.password 

在以下查询中

const valid = await argon2.verify(user.password ,options.password);

但它给了我错误

Property 'password' does not exist on type 'Promise<User | null>'

我不知道如何解决这个问题

【问题讨论】:

  • 你的函数是返回 Promise&lt;string | null&gt; 还是 Promise&lt;User | null&gt; ?顺便说一句,这些都没有password 的属性。

标签: javascript typescript react-fullstack micro-orm


【解决方案1】:

看起来您已经处于异步函数中。问题是您没有等待用户承诺完成。

试试这个:

// Check that this is really giving you an Entity Manager
const em = (await orm).em;

const users = await em.findOne(User, { username: options.username }); 
if (!users || users.length === 0) throw new Error('No user!');
const user = users[0];
const valid = await argon2.verify(user.password ,options.password);

【讨论】:

  • 让我澄清一下 - 我会稍微编辑一下代码
  • 它工作了非常感谢,兄弟你做得很好,继续努力。
猜你喜欢
  • 1970-01-01
  • 2015-09-10
  • 2019-09-20
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2017-10-23
相关资源
最近更新 更多