【问题标题】:Cannot resolve / reject a Promise无法解决/拒绝 Promise
【发布时间】:2020-09-17 06:03:42
【问题描述】:

我写了一个service 方法,它允许user 在我的restify API 中获得身份验证。 get 方法调用这个:

public async auth(email: string, password: string): Promise<Customer> {
    let connection = await DatabaseProvider.getConnection();
    const customer = await connection.getRepository(Customer).findOne({ email });

    try {
        let isMatch = await bcrypt.compare(password, customer!.password);

        if (!isMatch) throw 'Password did not match';
        Promise.resolve(customer);
    } catch (err) {
        Promise.reject('Authentication failed');
    }
}

我得到的问题是:

声明类型既不是“void”也不是“any”的函数必须返回一个值。

似乎Promise.resolve(customer) 没有返回任何内容,我也尝试使用return 前缀但同样的问题

【问题讨论】:

  • 它不返回任何东西,不,它只是创建一个已解决的承诺。为什么不只是 return customer;throw 'Authentication failed';,而是因为 async 函数已经返回了一个承诺?
  • @jonrsharpe 感谢您的提示!我是TypeScript 的新手。我采纳了你的建议,现在我得到了return customer这个错误:Type 'Customer | undefined' is not assignable to type 'Customer'. Type 'undefined' is not assignable to type 'Customer'
  • 那不是 TypeScript,只是 JS。我猜你明白了,因为 findOne 返回一个 Customer 或 undefined 如果没有找到,所以你需要处理第二种情况。
  • @jonrsharpe 好的,我实际上使用 `Promise`这是正确的吗?谢谢!
  • 我不知道,由你决定函数的API。例如,如果找不到客户,您是否希望消费者收到未定义的循环承诺或拒绝的承诺?

标签: typescript api es6-promise restify


【解决方案1】:
public async auth(email: string, password: string): Promise<Customer> {
    let connection = await DatabaseProvider.getConnection();

    const customer = await connection.getRepository(Customer).findOne({ email });

    let isMatch = await bcrypt.compare(password, customer!.password);

    if (!isMatch) throw 'Password did not match';

    if(customer)
      return customer;

    throw 'Customer is undefined';
}

我猜这应该可行...

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 2023-03-17
    • 1970-01-01
    • 2017-03-14
    • 2020-04-15
    • 2019-04-17
    • 1970-01-01
    • 2016-08-13
    • 2020-12-22
    相关资源
    最近更新 更多