我试图在问题和答案之间建立关联。我正在使用Bluebird的API .map
来确保仅在所有question.addAnswers(answer)
承诺完成后发生重定向。因此,在我的终端,我看到这样的事情:Bluebird Promise.map无法正常工作
done adding a answer to the question
done adding a answer to the question
finished
不过,我看到的是:
finished
done adding a answer to the question
done adding a answer to the question
因此,我假设Promise.map
是不工作的。我错过了什么?我怎样才能使它工作?
这里是我的代码:
router.post('/create', function(req, res) {
models.Question.create({
content: req.body.question
})
.then(function(question) {
if (!question) {
res.render('questions/new', {
error: "Question \"#{req.body.question}\" fails to be created"
});
} else {
// Update the new question to each user
models.User.findAll()
.then(function(users) {
users.forEach(function(user) {
user.addQuestion(question)
});
});
Promise.map(req.body.answers, function(answer){
return createAndAddToQuestion(question, answer, res)
})
.then(function(){
console.log('finished')
res.redirect("https://stackoverflow.com/questions/success/?question_id=" + question.id);
});
};
})
})
var createAndAddToQuestion = function(question, answer, res) {
models.Answer.create({
content: answer
})
.then(function(ans) {
if (ans) {
var promise = question.addAnswer(ans)
promise.then(function(){
console.log("done adding a answer to the question")
});
return question.addAnswer(ans);
} else {
res.render('questions/new', {
error: "Answer \"#{answer}\" fails to be created"
});
};
});
}
UPDATE 我刚刚更新createAndAddToQuestion
,所以它会返回一个承诺来代替。结果保持不变。 Promise.map
不起作用。
var createAndAddToQuestion = function(question, answer, res) {
models.Answer.create({
content: answer
})
.then(function(ans) {
if (ans) {
return question.addAnswer(ans).then(function() {
console.log('done')
})
} else {
res.render('questions/new', {
error: "Answer \"#{answer}\" fails to be created"
});
};
});
}
'createAndAddToQuestions'不会返回任何东西,但大概你希望它返回某种类型的Promise。也许你只是想'返回models.Answer.create ...'? – smarx
此外,您可能希望'return promise'而不是'return question.addAnswer(ans)'...否则,您将调用该函数两次。 – smarx
谢谢!这是一个错字。我将它改回来,但结果相同。 @smarx – WeiRoR