Async Mongoose callbacks in then statement
I believe your second then(..)
should look more like this:
.then(function(book){ return new Promise(function(resolve, reject){ BookModel.find({ name: book.name }, function(err, docs) { if (docs.length) { reject({message: "Book already exists"}); } else { resolve(book); } }); });})
You must not pass a callback to BookModel.find()
to get back a promise. Also you must not forget to return
the promises from your then
callbacks to continue chaining:
req.getValidationResult().then(result => { if (!result.isEmpty()) { throw 'Invalid payload'; } return new BookModel({ author: data.author, name: data.name, year: data.year });}).then(book => BookModel.find({name: book.name}).then(docs => book , err => { throw new Error("Book already exists"); })).then(book => book.save()).then(handler.onSuccess, handler.onError);
Also I fixed your problem with the invalid payload.