【问题标题】:How to add promise.all in Node.js Sequelize findOrCreate in loop?如何在Node.js中添加promise.all Sequelize findOrCreate in loop?
【发布时间】:2017-03-16 20:28:45
【问题描述】:

我在 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)

});

【问题讨论】:

    标签: javascript node.js promise sequelize.js


    【解决方案1】:

    您可以通过 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);
    });
    

    【讨论】:

    • 在这种情况下更喜欢map 而不是forEach
    • 使用 lambda 表示 const rooms = Promise.all(users.map(user => Rooms.findOrCreate({where: {user_id: user.get('id')}}))); rooms.then(...)
    【解决方案2】:

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

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

    【讨论】:

    • 带有 then 的链不起作用。然后在循环中执行每个传播执行。在forEach的所有迭代之后我需要执行一次
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2013-02-23
    • 2020-12-01
    • 2018-04-05
    • 2014-01-05
    • 1970-01-01
    相关资源
    最近更新 更多