如何在Node.js中添加promise.all在循环中sequelize findOrCreate?

时间:2016-11-03 09:50:32

标签: javascript node.js promise sequelize.js

我在sequelize中创建了两个模型。我得到了一系列结果“用户”而不是循环来获取或创建基于User.id的新“房间”。我想在完成后打印所有房间。我在控制台中得到了空数组,因为它是异步的。如何在创建所有房间后调用console.log?

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)

});

2 个答案:

答案 0 :(得分:4)

你可以通过Promise.all执行promises数组:

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

答案 1 :(得分:0)

尝试将console.log放入.then函数中。将它链接起来。扩展。我相信一组房间将作为参数传递给第一个回调:

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

或,

您可以尝试重构代码并将逻辑放在.then函数中。

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