【问题标题】:Returning a Promise since async function by default return a promise返回一个 Promise,因为异步函数默认返回一个 Promise
【发布时间】:2021-10-18 07:47:56
【问题描述】:
 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

【问题讨论】:

  • 是的,你可以直接throw new APIError(),因为它会返回一个 Promise 拒绝。
  • 你的意思是catch中的那个位吗?是的,你可以抛出一个异常,但不管怎样都可以。
  • 顺便说一句const savedUser = await userRepository.save(user); return savedUser; - 没意义...只是return userRepository.save(user);

标签: javascript node.js typescript promise


【解决方案1】:

但是返回 Promise 的目的是什么,因为异步函数默认返回一个 Promise

没有目的。其实,

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

等价于

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

【讨论】:

    猜你喜欢
    • 2020-07-09
    • 2023-03-13
    • 2020-07-09
    • 2017-10-16
    • 1970-01-01
    • 2017-02-10
    • 2020-06-20
    • 2017-09-13
    • 2018-04-13
    相关资源
    最近更新 更多