【问题标题】:Promise in Promise function: Can't push data into ArrayPromise 函数中的 Promise:无法将数据推送到数组中
【发布时间】:2019-03-07 11:36:18
【问题描述】:

我正在使用 sequelizeJS。我在 Promise 函数中有一个 Promise。我想做一个 Promise 函数来获取数据,然后将这个数据推入 Array 并返回这个 Array。

我尝试使用此代码,但没有成功。

function sequelize_conversation (conversation_id, req) {
  return new Promise((resolve, reject) => {
    var response = []
    for (let id of conversation_id) {
      db.ConversationPerson.findAll({ where: {'conversation_id': id, 'user_id': { [Op.ne]: req.user.user_id }} })
      .then(person => {
        console.log(person) // results: { 'id': 1, 'name': 'John' }
        response.push(person.dataValues)
      })
    }
    resolve(response)
  })
}

我得到的结果:

response = []

但我想得到:

response = [{ 'id': 1, 'name': 'John' }]

请查看我的代码并帮助我了解 Promise 函数中的 Promise。提前谢谢!

【问题讨论】:

  • promises 意味着异步代码......你正在解决任何 db.ConversationPerson.findAll 有机会做任何事情之前,更不用说完成

标签: javascript node.js promise sequelize.js


【解决方案1】:

promises 意味着异步代码...您在任何 db.ConversationPerson.findAll 有机会做任何事情之前就解决了,更不用说完成了

您的代码实际上比您想象的要简单得多

function sequelize_conversation (conversation_id, req) {
    var promises = [];
    for (let id of conversation_id) {
      promises.push(
        db.ConversationPerson.findAll({ where: {'conversation_id': id, 'user_id': { [Op.ne]: req.user.user_id }} })
        .then(data => {
          return data.dataValues
        })
      );
    }
    return Promise.all(promises);
}

或者如果 conversation_id 是一个实际的数组,并添加一点 ES6+ 的优点

const sequelize_conversation = (ids, req) => Promise.all(
    ids.map(conversation_id => 
        db.ConversationPerson.findAll({ 
            where: {
                conversation_id, 
                'user_id': { 
                    [Op.ne]: req.user.user_id 
                }
            }
        })
        .then(({dataValues}) => dataValues)
    )
);

【讨论】:

  • 我只想推送dataValues字段,兄弟
  • 好吧...我正在使用您发布的代码db.ConversationPerson.findAll({ where: {'conversation_id': id, 'user_id': { [Op.ne]: req.user.user_id }} }) - 您在.then 中声称person 是您想要的...所以,这就是上面的代码将解决的问题到
  • 即我没有改变进入数组的内容(嗯,有点)......我已经改变了它,以便它有机会到达那里 - 你的数据库函数是你的代码......兄弟
  • 或者,换一种说法......如果你的代码console.log(person) // results: { 'id': 1, 'name': 'John' }是准确的......那么我的代码将工作......你在哪里把console.log放在我的代码中?
  • 所以,你的原始代码也必须做到response.push(person.dataValues)@FeedGit 和console.log(person.dataValues)
猜你喜欢
  • 1970-01-01
  • 2020-08-25
  • 2019-06-06
  • 2019-01-04
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2014-10-25
  • 2016-05-06
相关资源
最近更新 更多