RobM RobM - 1 year ago 492
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 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;


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





Answer Source

You can execute array of promises through Promise.all:

var promises ={
    return Rooms.findOrCreate({where: {user_id: user.get('id')}});
    for(var key in dbRooms){
        _this.rooms.push(dbRooms[key][0].get({plain: true}));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download