如何使用诺言避免回调地狱? [英] How to use promise to avoid callback hell?
问题描述
所以我有一个帖子集合
{
id: String,
comments: [String], # id of Comments
links: [String], #id of Links
}
评论:
{
id:String,
comment:String,
}
Comments: { id: String, comment: String, }
链接:
{
id:String,
link:String,
}
Links: { id: String, link: String, }
查找包含评论和链接的帖子by id:
Find a post with comments and links belong to it by id:
Posts.findOne({id: id}, function(post) {
Comments.find({id: post.id}, function(comments) {
Links.find({id: post.id}, function(links) {
res.json({post: post, comments: comment, links: links})
})
})
})
如何使用Promise( http://mongoosejs.com/docs/promises.html )以避免回调地狱?
How to use Promise(http://mongoosejs.com/docs/promises.html) to avoid callback hell?
var query = Posts.findOne({id: id});
var promise = query.exec();
promise.then(function (post) {
var query1 = Comments.find({id: post.id});
var promise1 = query1.exec();
promise1.then(function(comments) {
var query2 = Links.find({id: post.id});
var promise2 = query2.exec();
promise2.then(function(links) {
res.json({post: post, comments: comment, links: links})
})
})
});
似乎没有好处......
Seems no good......
推荐答案
尝试使用此功能:
function getPost(id) {
return Post
.findOne({id: id})
.then( post => {
return post;
});
}
使用 Q 模块
function getCommentsAndLinks(post) {
return Q.all([
Comment.find({id: post.id}),
Links.find({id: post.id})
])
.done( results => {
let comments = results[0];
let links = results[1];
return [post, comments, links];
})
.catch( err => {
// handle err
})
$ b控制器上的$ b
on controller
getPost(postId)
.then(getCommentsAndLinks)
.then( results => {
let post = results[0];
let comments = results[1];
let links = results[2];
// more code here
})
.catch( err => {
// handle err
})
但我建议您不要保存IDS字符串,保存对象的实例,这样您就可以使用populate来获取评论和链接的所有数据,像这样:
but i suggest you not save string of IDS, save the instance of object, so you can use populate to get all data of comments and links, something like this:
Post
.findOne({id: id})
.populate('comments')
.populate('links')
.then( post => {
// here have the post with data of comments and links
});
这篇关于如何使用诺言避免回调地狱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!