如何发送承诺的对象数组

我已经尝试了很多,没有得到任何对我有用的东西。 我试着用promise.all和全局设置数组,但没有成功。

我想在MongoDB的三个集合中search,当查找匹配时,用信息设置一个对象并推送到一个数组。 最后,用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** }); 

对不起愚蠢的怀疑,但我花了很多时间试图find解决scheme,我决定诉诸社会。

谢谢!

如果我理解你的问题,你有多个承诺,并希望等待他们完成。 你可以用Promise.all()来做到这Promise.all()

如果一个Promise将失败Promise.all()也将失败。 但是,如果你像在你的例子中那样捕获它们,并且什么都不返回,那么我认为数组应该填入未定义的查询。 所以你可以过滤掉那些空的值,如果你想的话。

 const one = dbQueryOne.then(usr => ({ key: usr.val })) .catch(err => { console.log(err) }) const two = dbQueryTwo.then(usr => ({ key: usr.val })) .catch(err => { console.log(err) }) const three = dbQueryThree.then(usr => ({ key: usr.val })) .catch(err => { console.log(err) }) Promise.all([one, two, three]).then(arr => { res.send(arr.filter(val => val !== undefined )) }) 

usr => ({ key: val })只是usr => { return { key: val } }缩写