简体   繁体   English

如何在Node.js中添加promise.all在循环中顺序化findOrCreate?

[英]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. 我得到了结果“ Users”的数组,然后循环遍历以基于User.id来获取或创建新的“ Room”。 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? 创建所有房间后如何调用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)

});

You can execute array of promises through Promise.all: 您可以通过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);
});

Try putting console.log in .then function. 尝试将console.log放在.then函数中。 Chain it after .spread. .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. 您可以尝试重构代码并将逻辑放入.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
            })
        );
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM