从猫鼬的承诺中回复回应

时间:2016-07-24 16:55:15

标签: node.js express mongoose promise es6-promise

此问题的后续> Stopping response if document isn't found因为建议我使用Promise。

基本前提是,我希望节点返回"无法找到ID"如果我们无法在数据库中找到该ID,则会显示该消息。

v1.post("/", function(req, res) {

    // If the project_id isn't provided, return with an error.
    if ( !("project_id" in req.body) ) {
        return res.send("You need to provide Project ID");
    }

    // Check if the Project ID is in the file.
    helper.documentExists( ProjectsData, {project_id: req.body.project_id} )
        .then(function(c) {
            if ( c == 0 ) {
                return res.send("The provided Project Id does not exist in our database.");
            } else {
                var gameDataObj = req.body;

                GameData.addGameId(gameDataObj, function (err, doc) {
                    if (err) {
                        if (err.name == "ValidationError") {
                            return res.send("Please send all the required details.");
                        }
                        throw err;
                    };

                    res.json(doc);
              })
        };
    });
});

和helper.documentExists

module.exports = {
    documentExists: function(collection, query) {
        return collection.count( query ).exec();
    },
};

但是脚本在此之后继续运行并打印未找到的"所需数据"。

Output:
    required data not found
    1

我使用的是本机ES6 Promises。

var mongoose = require("mongoose");
    mongoose.Promise = global.Promise;

编辑:包括整个获取路线。 (将修复那些以后抛出的错误)

2 个答案:

答案 0 :(得分:1)

您的代码基本上会产生以下结果:

ProjectsData.count().then(...);
console.log("required data not found");

所以,当然第二个console.log()将会运行和打印。 .then()处理程序中发生的任何事情都不会在console.log()已经运行很久之后运行。即便如此,它也无法阻止其他代码运行。承诺不会让翻译“等待”。它们只是为您提供协调异步操作的结构。

如果你想使用promises进行分支,那么你必须在.then()处理程序内部而不是在它之后进行分支。

您没有充分展示您正在做的其他事情,以了解如何推荐完整的解决方案。我们需要查看您的其余请求,以便根据异步结果帮助您进行正确的分支。

你可能需要这样的东西:

ProjectsData.count( {project_id: req.body.project_id} ).then(function(c) {
    if ( c == 0 ) {
        return res.send("The provided Project Id does not exist in our database.");
    } else {
        // put other logic here
    }
}).catch(function(err) {
    // handle error here
});

答案 1 :(得分:1)

#######POINT 1#########
ProjectsData.count( {project_id: req.body.project_id} )

    .then(function(c) {
        #######POINT 3#########
        if ( c == 0 ) {
            console.log("1");
            return res.send("The provided Project Id does not exist in our database.");
            console.log("2");
        }
    });
#######POINT 2#########
//some other logic
console.log("required data not found");

在异步工作流程之后:在POINT 1之后,创建了承诺并附加了您的处理程序。现在POINT 2将继续,而(在某个未来的时钟,承诺得到解决,你到达POINT 3。

由于我对您的工作流程/目的的了解有限,我只想简单地将POINT 2代码放在POINT 3 else{}的{​​{1}}中(正如您在评论中正确猜到的那样)。 编辑:感谢@ jfriend00指出我的答案的前一版本中的一个严重错误。