2014-03-31 64 views
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); 
    }); 
} 
+0

任何錯誤/調試消息? – dopplesoldner

+0

@dopplesoldner沒有。我想我可能不完全理解異步本質。 'users.findAllSubjectNames'的末尾有一個'res.redirect(/)',它沒有在上面顯示。這會生效,並且'res.render(「newpost_template」...'即使doc返回爲null也沒有。是否有可能它已經執行了,它已經執行了,並且'res.redirect'已經執行了? – Squirrl

回答

0

我知道了。我必須將重定向和res.render放在if else子句中,所以只有一個會執行,並且只有在doc返回後纔會執行。我也不得不將它分成它自己的功能。

users.findAllSubjectNames(title, req.username, function(err, doc){ 
    "use strict" 
    if(err) return next(err); 

    //return res.redirect("/newpost") //res.render("newpost_template", {subject:title, username:req.username, body:req.body, tags:req.tags, errors:errors}); 
    if(doc === null){ 
     var errors = "Subject name already taken!"; 

     return res.render("newpost_template", {subject:title, username:req.username, body:req.body.body, tags:req.tags, errors:errors}); 
    } else { 
     classNumber(title, req, res, next); 
     return res.redirect("/profile");  
    } 
});