Promise in Promise function: Can't push data into Array

Feed

New Member
#1
I am using sequelizeJS. I have a Promise in Promise function. I want to make a Promise function to get data, then push this data into Array and return this Array.

I tried with this code but it's not success.
Mã:
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)
  })
}
Result I get:
response = []
But I want to get:
response = [{ 'id': 1, 'name': 'John' }]
Please review my code and help me understand about Promise in Promise function. Thank you in advance!
 

Admin

Administrator
Thành viên BQT
#2
promises imply asynchronous code ... you are resolving before any of the db.ConversationPerson.findAll has a chance to do anything, let alone complete

Your code is actually a lot simpler than you think
Mã:
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);
}
Or if conversation_id is an actual Array, and adding a little bit of ES6+ goodness
Mã:
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)
    )
);
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Chủ Đề Xem Nhiều

Top