1 回答

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
我終于Promise.all()用更優(yōu)雅的代碼解決了這個(gè)問題。
exports.getQuestion = (request, response) => {
let questionId = request.params.questionId;
// let question = {};
//let answers = [];
// get info except answers
// { content:XXX, answers: [] }
let fetchQuestion = firebase.firestore()
.doc(`questions/${questionId}`)
.get()
.then(doc => {
if(!doc.exists) {
throw Error('doc not exists');
}
return doc
})
.then(doc => {
return {
content: doc.data().content,
id: doc.id,
answers: []
}
})
.catch(error => {
console.log(error)
});
// return answers
let fetchAnswers = firebase.firestore()
.collection('answers')
.where('questionId','==',questionId)
.get()
.then(snapshot => {
if(snapshot.empty) {
console.log('no replies');
return [];
} else {
let answers = [];
snapshot.forEach(ans => {
// add answers to question
answers.push({
content: ans.data().content,
replies: [],
id: ans.id
})
})
return answers;
}
}).catch(error => {
console.log(error);
});
let fetchAnsReplies = fetchAnswers.then(answers => {
var promises = [];
answers.forEach(ans => {
var promise = firebase.firestore()
.collection('repliesToAnswers')
.where('answerId','==',ans.id)
.get()
.then(snapshot => {
if(snapshot.empty) {
console.log('no reply');
return;
} else {
snapshot.forEach(reply => {
ans.replies.push({
content: reply.data()
})
})
}
}).catch(error => {
console.log(error);
})
promises.push(promise);
})
return Promise.all(promises).then(() => {
return answers;
})
}).catch(error => {
console.log(error);
})
return Promise.all([fetchQuestion,fetchAnswers, fetchAnsReplies])
.then(results => {
return response.json({...results[0],answers:results[2]});
}).catch(error => {
console.log(error);
response.status(500).json({
error: error.code
})
})
}
添加回答
舉報(bào)