【发布时间】:2017-04-05 04:39:06
【问题描述】:
我尝试了很多,但没有得到任何对我有用的东西。 我尝试使用 promise.all 并在全局范围内设置数组,但没有成功。
我想在 MongoDB 上的三个集合中搜索,当找到匹配时,使用信息设置一个对象并推送到一个数组。最后,使用 objects 数组发送响应。
router.post('/certificado', (req, res) => {
let cpf = splita(req.body.cpf)
let array = []
function pesquisaProjeto(cpf) {
return new Promise(function (fulfill, reject) {
ProjetoSchema.find({'integrantes.cpf':cpf}, 'integrantes.$ nomeProjeto -_id',(err, usr) => {
if (err) return reject(err)
fulfill(usr)
});
})
}
function pesquisaAvaliador(cpf) {
return new Promise(function (fulfill, reject) {
avaliadorSchema.find({'cpf':cpf}, 'nome -_id',(err, usr) => {
if (err) return reject(err)
fulfill(usr)
})
})
}
function pesquisaParticipante(cpf) {
return new Promise(function (fulfill, reject) {
participanteSchema.find({'cpf':cpf}, 'nome eventos -_id', (err, usr) => {
if (err) return reject(err)
fulfill(usr)
})
})
}
pesquisaProjeto(cpf)
.then(usr => {
let participante = ({
tipo: usr[0].integrantes[0].tipo,
nome: usr[0].integrantes[0].nome
})
array.push(participante)
console.log(participante)
})
.catch(err => console.log("Não encontrou nada nos projetos. " + err.message))
pesquisaAvaliador(cpf)
.then(usr => {
let participante = {
tipo: "Avaliador",
nome: usr[0].nome
}
array.push(participante)
console.log(array)
})
.catch(err => console.log("Não encontrou nada nos avaliadores. " + err.message))
pesquisaParticipante(cpf)
.then(usr => {
let participante = ({
tipo: "Participante",
nome: usr[0].nome,
eventos: usr[0].eventos
})
array.push(participante)
console.log(array)
})
.catch(err => console.log("Não encontrou nada nos participantes dos eventos. " + err.message))
**Anything like res.send(array) that I was tired to try**
});
对于愚蠢的疑问,我很抱歉,但我花了很多时间试图找到我决定求助于社区的解决方案。
谢谢!
【问题讨论】:
-
为什么
promise.all不起作用? -
不知道。当我在
promise.all的.then()尝试res.send(array)时,没有任何东西发送到前面。认为在 Promise 和数组声明中的 push 可能有问题。 -
请告诉我们您如何尝试使用
Promise.all。 -
@RicardoSwarovsky 将您的解决方案添加为答案,而不是对您的问题进行编辑。
标签: javascript node.js express promise