【发布时间】: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