简体   繁体   English

Node.js 均衡在 forEach 循环中创建新行

[英]Node.js Sequalize creating new rows in forEach loop

I'm trying to create new rows in the database using Sequalize ORM.我正在尝试使用 Sequalize ORM 在数据库中创建新行。 I receive an array of collections from req.query.collections .我从 req.query.collections 收到一组req.query.collections For each of those collections I need to create a new userCollection .对于每个 collections 我需要创建一个新的userCollection If none userCollection s were created, I wanna respond with internal server error (line 41), otherwise return an array of objects with newly created userCollections .如果没有创建userCollection ,我想以内部服务器错误(第 41 行)进行响应,否则返回一个包含新创建的userCollections的对象数组。

The problem is, I keep getting an internal server error when I make test requests from Postman.问题是,当我从 Postman 发出测试请求时,我不断收到内部服务器错误。 When I check my database, I see that those userCollections were created, so no error occurred.当我检查我的数据库时,我看到这些userCollections已创建,因此没有发生错误。

I know why this happens: because userCollection.build({ stuff }).save() returns a promise.我知道为什么会这样:因为userCollection.build({ stuff }).save()返回 promise。 So when I try to console.log userCollections from within .then() statement, I get an array with a newly created collections, just like I should.因此,当我尝试从 .then .then()语句中 console.log userCollections时,我得到一个包含新创建的 collections 的数组,就像我应该做的那样。 But by that time server has already responded with internal server error.但是到那时服务器已经响应内部服务器错误。

Here's my function code:这是我的 function 代码:

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

Posting the solution发布解决方案

Thanks to Sebastien Chopin who created this tutorial: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404感谢创建本教程的塞巴斯蒂安肖邦: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404

So I added this function:所以我添加了这个 function:

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

And instead of collections.forEach...(blah blah) (line 10 of the code posted in the question) I do:而不是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));
}

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

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