我正在尝试用Mongoose 4.5.4链接ES6 Promise

public static signup(req: express.Request, res: express.Response) {
    UserModel.findOne({ email: req.body.email }).exec()
    .then(existingUser => {
        if(existingUser) {
            return res.send({ message: 'Email is in use' });
        }

        return UserModel.create({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            email: req.body.email,
            password: req.body.password
        });
    })
    .then(user => {
            return res.send({ token: AuthUtils.createJWT(user)});
    })
    .catch(err => {
        console.log(err);
    });
}

但是,当我尝试return UserModel.create(...)时,Typescript引发以下错误:
Argument of type '(existingUser: IUser & _Model<IUser> & EventEmitter) => Response | MongoosePromise<IUser & _Model...' is not assignable to parameter of type '(...args: (IUser & _Model<IUser> & EventEmitter)[]) => void | (IUser & _Model<IUser> & EventEmitt...'. Type 'Response | MongoosePromise<IUser & _Model<IUser> & EventEmitter>' is not assignable to type 'void | (IUser & _Model<IUser> & EventEmitter) | PromiseLike<IUser & _Model<IUser> & EventEmitter>'. Type 'Response' is not assignable to type 'void | (IUser & _Model<IUser> & EventEmitter) | PromiseLike<IUser & _Model<IUser> & EventEmitter>'. Type 'Response' is not assignable to type 'PromiseLike<IUser & _Model<IUser> & EventEmitter>'. Property 'then' is missing in type 'Response'..create()返回一个Promise,所以我看不到这将是一个问题。

任何帮助,将不胜感激。

最佳答案

通过在promise的响应上使用existing标志,将控制流添加到现有用户。
例子:

public static signup(req: express.Request, res: express.Response) {
      UserModel.findOne({ email: req.body.email }).exec()
      .then(existingUser => {
          if(existingUser) {
              return Promise.resolve({
                user: existing,
                existing: true
              });
          }
          return UserModel.create({
              firstName: req.body.firstName,
              lastName: req.body.lastName,
              email: req.body.email,
              password: req.body.password
          }).then((user) => {
            return Promise.resolve({
              existing: false,
              user: user
            });
          });
      })
      .then(response => {
        if (response.existing) {
          return res.send({ message: `Email ${response.user.email} is in use` });
        } else return res.send({ token: AuthUtils.createJWT(response.user)});
      })
      .catch(err => {
          console.log(err);
      });
  }

关于node.js - 用 typescript 链接 Mongoose 中的ES6 promise ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38552871/

10-10 17:02