返回一个承诺,因为异步函数默认返回一个承诺


async add(model: IUser): Promise<User | null> {
const { username, role, password, email } = model;
const user = new User();
user.username = username;
user.role = role;
user.password = password;
user.email = email
const userRepository = getRepository(User);
try {
const savedUser = await userRepository.save(user);
return savedUser;
} catch (e) {
console.log(e);
return Promise.reject(new APIError('User Already exists', Err.EmailAlreadyExists));
}
以上代码用于将用户数据保存到mysql数据库中。它工作得很好。但是返回Promise的目的是什么呢?因为async函数默认返回一个Promise

但是返回Promise的目的是什么呢?因为async函数默认返回一个Promise

没有目的。实际上,

return Promise.reject(new APIError('User Already exists', Err.EmailAlreadyExists));

等价于

throw new APIError('User Already exists', Err.EmailAlreadyExists);

最新更新