En este momento, estoy trabajando en una RESTful-API con express y mongoose y ahora tengo un problema.
Primero, mi método:
public create() : Promise<UserDocument> { return new Promise((user) => { User.exists(this.username).then((exists) => { if (exists) { throw Errors.mongoose.user_already_exists; } else { UserModel.create(this.toIUser()).then((result) => { user(result); }).catch(() => { throw Errors.mongoose.user_create }); } }).catch((error) => { throw error; }) }); }Obtengo un rechazo de promesa no controlado cuando ejecuto este método. Esto sucede incluso si manejo el error cuando ejecuto el método de esta manera:
User.fromIUser(user).create().then(() => { return response.status(200).send({ message: "Created", user }); }).catch((error) => { return response.status(500).send({ message: error }); });Seguimiento completo de la pila:
(node:23992) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): User already exists (node:23992) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.¿Cómo puedo evitar esta situación?
Gracias por tu ayuda, felix
¡Encontré la solución! Simplemente use "resolver, solicitar" para crear una promesa.
Aquí está ahora mi método:
public create() : Promise<any> { return new Promise((resolve, reject) => { User.exists(this.username).then((exists) => { if (exists) { reject( Errors.mongoose.user_already_exists); } else { UserModel.create(this.toIUser()).then((result) => { resolve(result); }).catch(() => { reject(Errors.mongoose.user_create); }); } }).catch((error) => { reject(error); }) }) } Si llama al método ahora, puede usar el método catch() y ¡todo funciona! Llámalo así:
User.fromIUser(user).create().then((user) => { return response.status(200).send({ message: "Created", user }); }).catch((error) => { return response.status(500).send({ message: error }) })