gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:36:58 24 4
gpt4 key购买 nike

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

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

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

这是我的函数代码:

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

最佳答案

发布解决方案

感谢创建本教程的 Sebastien Chopin:
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));
}

关于Node.js Sequelize 在 forEach 循环中创建新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58123750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com