如何正确使用猫鼬诺言

时间:2018-08-20 16:54:18

标签: javascript node.js mongoose

我一直在节点js中处理这段代码,它的问题是有时它可以工作,但有时却不行(我用猫鼬):

promises.push(Quote.findOne({_id: req.params.quoteId}).then((quote) => {
        //retrive the quote's comments
        var commentPromises = [];
        for(var i = 0; i < quote.comments.length; i++){
            commentPromises.push(Comment.findOne({_id: quote.comments[i].commentId}));
        }
        Promise.all(commentPromises).then((comments) => {
            console.log(comments)
            //remove comment from it's author's list of submitted comments
            var commentRemovePromises = [];
            comments.forEach((comment) => {
                //for each comment retrive its author
                commentRemovePromises.push(User.findOne({_id: comment.author}))
            })
            Promise.all(commentRemovePromises).then((commentAuthors) =>  {
                commentAuthors.forEach((commentAuthor) => {
                    //for each author delete the comment id from his list of sumitted comments
                    for(var i = 0; i < commentAuthor.comments.length; i++){
                        if(commentAuthor.comments[i].commentId === comments[i].id){
                            var position = i;
                        }else{
                            continue;
                        }
                    }
                    User.findOne({_id: commentAuthor.id}).then((commentAuthor1) => {
                        commentAuthor1.comments.splice(position, 1);
                        commentAuthor1.save();
                    })
                })
            })
            //remove comment id from all users lists' of comments that they hearted
            //remove comment id from the quote's author's list of otherUsersComments
        })
    }))

    Promise.all(promises).then(() => {
        //delete all comments under this quote
        Comment.find({quoteId: req.params.quoteId}).remove().then(() => {
            Quote.findOneAndRemove({_id: req.params.quoteId}).then(() => {
                res.json() 
            });
        })
    });
});

我通常会得到注释(第8行)返回[null,null等]数组。问题似乎是console.log(comments)在comments数组获取任何值之前运行,但是这没有任何意义,因为我使用了Promise.all()。 在此先感谢;)

0 个答案:

没有答案