【问题标题】:Node.js Sequalize creating new rows in forEach loopNode.js Sequelize 在 forEach 循环中创建新行
【发布时间】:2019-10-26 05:15:31
【问题描述】:

我正在尝试使用 Sequalize ORM 在数据库中创建新行。我收到了来自req.query.collections 的一系列集合。对于每个集合,我需要创建一个新的userCollection。如果没有创建 userCollections,我想以内部服务器错误(第 41 行)进行响应,否则返回带有新创建的 userCollections 的对象数组。

问题是,当我从 Postman 发出测试请求时,我不断收到内部服务器错误。当我检查我的数据库时,我看到那些 userCollections 已创建,所以没有发生错误。

我知道为什么会这样:因为userCollection.build({ stuff }).save() 返回了一个承诺。因此,当我尝试从 .then() 语句中 console.log userCollections 时,我得到一个包含新创建的集合的数组,就像我应该做的那样。但到那时服务器已经响应内部服务器错误。

这是我的功能代码:

exports.addCollections = async (req, res, next) => {
    const libraryId = req.params.libraryId;
    const collections = req.query.collections;

    if (!collections)
        next(Boom.forbidden());

    const userCollections = [];

    collections.forEach(async (collectionId, index) => {
        const collection = await Collection.findByPk(collectionId);

        if (!collection)
            return next(Boom.notFound());

        userCollection.build({
            user_id: req.user.id,
            library_id: libraryId,
            public_collection_id: collection.id,
            title: collection.title,
            description: collection.description
        })
            .save()
            .then(newUserCollection => {
                userCollections.push(newUserCollection.get({ plain: true }));

                // should be printed first, but comes second
                // prints out the array with newly created record
                console.log(userCollections);
            })
            .catch(error => {
                console.log(error);
            });
    });

    // should be printed second, but comes first
    // prints out empty array
    console.log(userCollections);

    if (userCollections.length === 0) {
        next(Boom.internal());
    }

    res.json(userCollections);
}

【问题讨论】:

    标签: node.js asynchronous foreach promise sequelize.js


    【解决方案1】:

    发布解决方案

    感谢创建本教程的塞巴斯蒂安肖邦: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404

    所以我添加了这个功能:

    const asyncForEach = async (array, callback) => {
        for (let index = 0; index < array.length; index++) {
            await callback(array[index], index, array)
        }
    }
    

    而不是collections.forEach...(blah blah)(问题中发布的代码的第10行)我这样做:

    try {
        await asyncForEach(collections, async (collectionId, index) => {
            const collection = await Collection.findByPk(collectionId);
    
            if (!collection)
                return next(Boom.notFound());
    
            userCollection.build({
                user_id: req.user.id,
                library_id: libraryId,
                public_collection_id: collection.id,
                title: collection.title,
                description: collection.description
            })
                .save()
                .then(newUserCollection => {
                    userCollections.push(newUserCollection.get({ plain: true }));
                    console.log(userCollections);
                })
                .catch(error => {
                    console.log(error);
                });
        })
    } catch (err) {
        return next(Boom.internal(err.message));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      相关资源
      最近更新 更多