KitKit
KitKit

Reputation: 9533

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

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.

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!

Upvotes: 0

Views: 540

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

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

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

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)
    )
);

Upvotes: 1

Related Questions