本文介绍了then语句中的异步Mongoose回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用来自Mongoose
这是我的代码
req.checkBody(BookManager.SCHEME);
req.getValidationResult()
.then(function (result) {
if (!result.isEmpty()) {
handler.onError('Invalid payload');
return;
}
return new BookModel({
author: data.author,
name: data.name,
year: data.year
});
})
.then((book) => {
BookModel.find({name: book.name}, function (err, docs) {
if (docs.length) {
throw new Error("Book already exists");
} else {
return book;
}
});
})
.then((book) => {
book.save();
})
.then((saved) => {
handler.onSuccess(saved);
})
.catch((error) => {
handler.onError(error.message);
});
从上面的代码中可以看到.我正在检查这种书是否已经存在,为了做到这一点,我使用了异步查找方法,该方法在主要的程序计数器"进一步执行之后被调用.
As you can see from the code above. I am checking whether such book already exists and in order to do this I use async find method that is called after the main "program counter" has gone further.
我该如何解决这个问题?
How can I solve this problem ?
还请告诉我我是否选择了合适的等待时间来实现我的用例?也许我做错了,还有其他一些最佳实践可以解决这个问题.
Also please tell me whether I have chosen the right wait to implement my use case ? Maybe I am doing it wrong and there are some other best practices to handle this.
推荐答案
我相信您的第二个then(..)
应该看起来像这样:
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);
}
});
});
})
这篇关于then语句中的异步Mongoose回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!