我试图用Mongoose 4.5.4
链接ES6承诺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,所以我看不出这是怎么回事。
任何帮助都将不胜感激。
答案 0 :(得分:3)
通过在promise的响应上使用<body>
<div class='div1'></div>
<div class='div2'></div>
</body>
标志,将控制流添加到现有用户。
例如:
existing
答案 1 :(得分:0)
我实际上最终为ES6构建了我的项目,以便我可以使用async/await
它允许我彻底简化代码。
public static async signup(req: express.Request, res: express.Response) {
try {
let user = await UserModel.findOne({ email: req.body.email }).exec()
if(user) {
throw `Email ${user.email} is in use`;
}
if(environment.debug) console.log(`Creating new user ${req.body.firstName} ${req.body.lastName} with email ${req.body.email}`);
user = await UserModel.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
});
return res.send({ token: AuthUtils.createJWT(user)});
} catch(e) {
console.log(e);
res.send({ error: e });
}
}