【问题标题】:How to send a object array with promise如何发送带有承诺的对象数组
【发布时间】: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


【解决方案1】:

如果我理解您的问题,您有多个承诺,并希望等待所有承诺都完成。你可以通过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 } } 的缩写

【讨论】:

  • 非常感谢!这真的解决了问题!
猜你喜欢
  • 2017-12-14
  • 2019-01-05
  • 2015-10-24
  • 2016-10-15
  • 2017-02-28
  • 2019-07-06
  • 2021-03-22
  • 2016-09-26
相关资源
最近更新 更多