【发布时间】:2016-11-28 00:17:26
【问题描述】:
从这个问题跟进 > 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;
编辑:包括整个获取路线。 (稍后会修复那些抛出错误)
【问题讨论】:
-
console.log("required data not found");将运行任何计数,因为它超出了承诺然后回调。 -
哦。我假设 Promise 会在它下面的任何东西之前运行。我的假设错了吗?我应该在 else 块下添加其余的逻辑吗?
-
是的,你应该这样做。请参阅我的答案以获得一些见解!
-
如果 Promise 让你的代码等待它们,那会让它们变得毫无用处,不是吗? ;)
-
取决于你的依赖。基于此,您可以分支代码。这可以帮助您注意只有关键区域等待 promise 被解决,而其他区域则继续不受干扰。
标签: node.js express mongoose promise es6-promise