3

I create two models in sequelize. I got array of results "Users" and than loop through to get or create new "Room" based on User.id. I want to print all rooms after all is done. I got empty array in console, because its asynchronious. How can I call console.log after creating all Rooms?

var Users = sequelize.import(__dirname + "/../models/own/user");
var Rooms = sequelize.import(__dirname + "/../models/own/room");    
var _this = this;

this.users = [];
this.rooms = [];

Users.findAll().then(function(users) {
    _this.users = users;

    users.forEach(function(user){

        Rooms.findOrCreate({where: {user_id: user.get('id')}})
        .spread(function(room, created) {
          _this.rooms.push(
            room.get({
              plain: true
            })
          );

        });

    });

    console.log(_this.rooms)

});
0

2 Answers 2

7

You can execute array of promises through Promise.all:

var promises = users.map(function(user){
    return Rooms.findOrCreate({where: {user_id: user.get('id')}});
});
Promise.all(promises).then(function(dbRooms){
    for(var key in dbRooms){
        _this.rooms.push(dbRooms[key][0].get({plain: true}));
    }
    console.log(_this.rooms);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Prefer map to forEach in this case.
With a lambda it's const rooms = Promise.all(users.map(user => Rooms.findOrCreate({where: {user_id: user.get('id')}}))); rooms.then(...)
0

Try putting console.log in .then function. Chain it after .spread. I believe an array of the rooms will be passed as an argument to the first callback:

.then(function(rooms){
    ...
})

or,

you may try to refactor your code and put your logic in a .then function.

Rooms.findOrCreate({where: {user_id: user.get('id')}})
.then(function(rooms, created) {
    var room;

    for(var i in rooms){
        room = rooms[i];

        _this.rooms.push(
            room.get({
                plain: true
            })
        );
    }
});

1 Comment

The chain with then doesn't work. Then is executed every spread execution in a loop. I need sth executed once after all iteration of forEach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.