從這個問題的後續>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承諾。
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
編輯:包括整個獲取路線。 (以後會解決這些拋ERR)
'console.log(「required data not found」); ''''''''''''會運行任何計數,因爲它超出了承諾然後回調 – Iceman
哦,我認爲Promise會在它低於它的任何東西之前運行。否則阻止? – DragoonHP
是的,你應該。看到我的答案有點洞察力! – Iceman