0
我想我對這個回調感到困惑,但是我有以下代碼,並且當主題名稱無效時我試圖返回newpost_template
。我認爲我的邏輯是正確的,但並沒有回來。它正在通過。它工作得很好,當!title
時呈現newpost_template
。歡迎任何建議,謝謝。如何返回節點回調到mongo並重定向?
這工作:
if (!title) {
var errors = "Post must contain a title";
return res.render("newpost_template", {
subject: title,
username: req.username,
body: req.body,
tags: req.tags,
errors: errors
});
}
這不起作用:
users.findAllSubjectNames(title, req.username, res, req, function(err, doc) {
"use strict"
if (err) return next(err);
console.log('doc');
console.log(doc);
if (doc === null) {
console.log('this shows');
var errors = "Subject name already taken!";
console.log('this also shows');
//return res.redirect("/newpost ")
return res.render("newpost_template ", {
subject: title,
username: req.username,
body: req.body,
tags: req.tags,
errors: errors
});
console.log('this doesnt show');
}
});
this.findAllSubjectNames = function(title, user, res, req, callback) {
"use strict";
users.find({}, {
"teacher.subject ": 1
}).toArray(function(err, result) {
"use strict ";
if (err) return callback(err, null);
console.log('result');
for (var r = 0; r < result.length; r++) {
for (var t = 0; t < result[r].teacher.length; t++) {
if (result[r].teacher[t].subject == title && result[r]._id != user) {
console.log('INVALID!');
return callback(err, null);
//return res.redirect("/newpost ")
}
}
}
return callback(err, result);
});
}
任何錯誤/調試消息? – dopplesoldner
@dopplesoldner沒有。我想我可能不完全理解異步本質。 'users.findAllSubjectNames'的末尾有一個'res.redirect(/)',它沒有在上面顯示。這會生效,並且'res.render(「newpost_template」...'即使doc返回爲null也沒有。是否有可能它已經執行了,它已經執行了,並且'res.redirect'已經執行了? – Squirrl