I am trying to build associations between a question and answers. And I am using to use Bluebird's API .map
to make sure a redirect only happens after all the question.addAnswers(answer)
promises are done. Therefore, in my terminal, I should see something like this:
done adding a answer to the question
done adding a answer to the question
finished
However, what I see is:
finished
done adding a answer to the question
done adding a answer to the question
Therefore, I assume the Promise.map
is not working at all. Did I miss something? How can I make it work?
Here is my code:
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("/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
I just update the createAndAddToQuestion
, so it will return a promise instead. Outcome stays the same. Promise.map
is not working.
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"
});
};
});
}