RobM RobM - 1 month ago 38
Javascript Question

How to add promise.all in Node.js Sequelize findOrCreate in loop?

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)

});

Answer

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